iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 26
0
Software Development

Kotlin 30 天,通過每天一個小 demo 學習 Android 開發系列 第 26

Kotlin 開發第 26 天 ActionSend ( Intent-Filter )

ActionSend

和 iOS 的 Share Extension 一樣, Android 也能夠將內容分享到其他 App 上面,
比如一張照片想要從自己的 App 分享到 Facebook, Line, Wechat, Weibo 等等。


Transfer Money

https://ithelp.ithome.com.tw/upload/images/20171229/20107329qHbNfIWBbQ.png
這次要準備兩個 App 其中一個負責發送資料 (ActionSend App),另外一個負責接收 (ActionRecive App)


ActionSend App

在這個 App 裡面我們需要提供一個 EditView 讓使用者可以填入金額,然後通過 Transfer 按鈕進行傳送。
https://ithelp.ithome.com.tw/upload/images/20171229/20107329k5JDbGkZcj.png

Intent

就和傳送資料到另外一個 Activity 相同,我們會需要用到 Intent,並且指定資料類型和資料內容。

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 的位置)

https://ithelp.ithome.com.tw/upload/images/20171229/20107329aHHU1IfCOg.png

Intent-Filter

為了能夠接收到消息,需要到 AndroidManifest.xml 中增加 intent-filter 並指定會接收的 Activity 對象

<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 類型。

if(Intent.ACTION_SEND.equals(intent.action) && intent.type != null){
    if("text/plain".equals(intent.type)){
        receiveTextHandler(intent)
    }
}

然後將 intent 中的 text 取出來顯示到畫面上就完成了。

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 就非常不同了。

參考


上一篇
Kotlin 開發第 25 天 FaceRecognizer (FaceDetector)
下一篇
Kotlin 開發第 27 天 ShakeShake ( SensorManager )
系列文
Kotlin 30 天,通過每天一個小 demo 學習 Android 開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言