2019年2月20日 星期三

Android 如何傳遞訊息至其他 app/how to send intent to other app

如何從A app 發送 intent 至 B app

首先在 A app 寫一個點擊事件,點擊後發送


  private fun btnClick() {

Intent().apply {
action = "update"
putExtra("title", "title")
putExtra("id", "123456")  
putExtra("date", "2018-06-22 12:21:34")
  
flags = Intent.FLAG_INCLUDE_STOPPED_PACKAGES

//傳送至特定的 app,不過好像收不到
//            component = ComponentName("com.xxx.xxx",
//                "com.xxx.xxx.xxx.MyReceiver")

sendBroadcast(this)
}

    }

接著要接收資料的 B app,如果是 android 版本是8.0以上必須動態註冊 Receiver,8.0要在 manifest  使用必須自定義權限(未實作),因為 8.0 管得很嚴,若非8.0在 manifest 註冊 Receiver 便可。



Android 8.0 以上

在 activity 的 onResume 註冊,記得要解除註冊

   override fun onResume() {
        super.onResume()
        registerReceiver(MyReceiver(), IntentFilter("update"))
    }



MyReceiver


class MyReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {

        val action = intent.action
        val id = intent.extras?.getString("id")
        val date = intent.extras?.getString("date")
    }
}



未滿 Android 8.0 

在 manifest 註冊就完成了(灑花~

 <receiver android:name=".MyReceiver"
                  android:enabled="true"
                  android:exported="true">
            <intent-filter>
                <action android:name="update" />
            </intent-filter>
        </receiver>


android:exported="true"
若沒有 intent-filter 預設為false,有則為true
若設為 false 外部無法調用

因為公司只有少數幾個人可以發推播,要 debug 需要勞煩很多人,於是自己寫一個 app 作為推播測試用。這樣的寫法只要action 跟 intent filter 條件相同就會吃的到,如果要增加安全性就需要使用自定義權限去限制,發送方與接收方須持有相同權限名稱才可以接收。

大概4這樣。

沒有留言:

張貼留言