Reputation: 949
I am trying to send broadcast from App A to App B on Android 11.
Here is the receiver App B:
Manifest:
<receiver android:name="com.example.my_test.TestReceiver"
android:enabled="true"
android:permission="com.example.my_test.broadcast_permission">
<intent-filter>
<action android:name="com.example.my_test.receive_action"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
Receiver class:
class TestReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("MY_TAG", "received: ${intent?.getIntExtra("data", 0)}")
}
}
Here is sender App A:
Manifest:
<uses-permission android:name="com.example.my_test.broadcast_permission"/>
...
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
...
Sender code (inside MainActivity
):
findViewById<Button>(R.id.button).setOnClickListener {
val intent = Intent("com.example.my_test.receive_action")
intent.addCategory("android.intent.category.DEFAULT")
intent.component = ComponentName("com.example.my_test", "com.example.my_test.TestReceiver")
intent.putExtra("data", 69)
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
sendBroadcast(intent, "com.example.my_test.broadcast_permission")
}
This is everything I have tried so far. Also not sure if anything regarding broadcast permission is wrong here. Nothing works, the TestReceiver
class never logs anything.
I have also tried with android:exported="true"
If anyone knows where I am making a mistake, kindly help. If not possible, is there any other way to pass data from one app to another? Thanks.
Upvotes: 1
Views: 5893
Reputation: 949
Solved. Here are some points:
<permission>
tag. I missed this one.Category
is not necessary. Also no need to declare the permission inside sendBroadcast()
<uses-permission>
in App A (sender) is necessary.ComponentName
or package name (using setPackage()
) needs to be mentioned in Android 11.Here's the corrected code:
Here is the receiver App B:
Manifest:
<permission android:name="com.example.my_test.broadcast_permission"/>
...
<application>
...
<receiver android:name="com.example.my_test.TestReceiver"
android:permission="com.example.my_test.broadcast_permission">
<intent-filter>
<action android:name="com.example.my_test.receive_action"/>
</intent-filter>
</receiver>
...
</application>
...
Receiver class: No change.
Here is sender App A:
Manifest: No change
Sender code (inside MainActivity
):
findViewById<Button>(R.id.button).setOnClickListener {
val intent = Intent("com.example.my_test.receive_action")
intent.component = ComponentName("com.example.my_test", "com.example.my_test.TestReceiver")
// if exact receiver class name is unknown, you can use:
// intent.setPackage("com.example.my_test")
intent.putExtra("data", 69)
sendBroadcast(intent)
}
Upvotes: 1