和 iOS 的 Share Extension 一樣, Android 也能夠將內容分享到其他 App 上面,
比如一張照片想要從自己的 App 分享到 Facebook, Line, Wechat, Weibo 等等。
Transfer Money
這次要準備兩個 App 其中一個負責發送資料 (ActionSend App),另外一個負責接收 (ActionRecive App)
ActionSend App
在這個 App 裡面我們需要提供一個 EditView 讓使用者可以填入金額,然後通過 Transfer 按鈕進行傳送。
Intent
就和傳送資料到另外一個 Activity 相同,我們會需要用到 Intent,並且指定資料類型和資料內容。
1 2 3 4 5 |
val intent = Intent() intent.action = Intent.ACTION_SEND intent.putExtra(Intent.EXTRA_TEXT, layout_main_shareEditText.text.toString()) intent.type = "text/plain" startActivity(intent) |
ActionReceive App
在這個 App 裡面,我們會將接收到的 text 顯示在畫面上(現在顯示 0 的位置)
Intent-Filter
為了能夠接收到消息,需要到 AndroidManifest.xml 中增加 intent-filter 並指定會接收的 Activity 對象
1 2 3 4 5 6 7 |
<activity android:name=".ReceiverActivity"> <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain" /> </intent-filter> </activity> |
ReceiverActivity
在 onCreate 的地方,我們就能夠嘗試去接收 intent 資訊,並判斷 intent 類型。
1 2 3 4 5 |
if(Intent.ACTION_SEND.equals(intent.action) && intent.type != null){ if("text/plain".equals(intent.type)){ receiveTextHandler(intent) } } |
然後將 intent 中的 text 取出來顯示到畫面上就完成了。
1 2 3 4 |
val text = intent.getStringExtra(Intent.EXTRA_TEXT) if(!text.isEmpty()){ layout_receiver_received_textView.text = "$ $text" } |
筆記
- TODO: 從 App-A 分享內容到 App-B 以後,如何處理完再進行回傳的實作。
- 概念:我從 App-A 做 intent 而 App-B 的 ReceiveActivity 接收了,
這時我發現在 Menu 上看起來是 App-A 把 App-B 的 Activity 給載入了,
而不是真的開啟 App-B,這邊和 iOS 就非常不同了。
參考
- 官方文件 – 與其他應用程式互動
- 可以到 Github 上看對應的 Source Code