How to send a custom broadcast action to receivers in manifest?
I use Android 8.
Then you have to use an explicit Intent
, one that identifies the receiver, such as:
sendBroadcast(new Intent(this, MyReceiver.class).setAction("MyAction"));
See Broacast limitations in Android 8 release docs.
If you have multiple receivers, you can send broadcast to all the receivers using only custom action defined in manifest for that you need to add the following flag while sending broadcast
Note: I have used adb to test it on Android 10, you can add it in application
FLAG_RECEIVER_INCLUDE_BACKGROUND = 0x01000000
adb shell am broadcast -a MyAction -f 0x01000000
In Kotlin:
val intent = Intent(this, MyBroadCastReceiver::class.java)
intent.addCategory(Intent.CATEGORY_DEFAULT)
intent.action = "my.custom.broadcast"
sendBroadcast(intent)
In Android 8 onwords
- We need to provide the explicite class for handling i.e setcomponent param along with action
Example :
private void triggerBroadCast(String firstFavApp, String secondFavApp) {
Intent intent = new Intent("FavAppsUpdated");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.putExtra("FIRST_FAV_APP", firstFavApp);
intent.putExtra("SECOND_FAV_APP", secondFavApp);
intent.setComponent(new
ComponentName("com.android.systemui",
"com.android.systemui.statusbar.phone.FavAppsChanged"));
Log.i(TAG, "Trigger Fav Apps" + firstFavApp + " " + secondFavApp);
favouriteContract.getAppContext().sendBroadcast(intent);
}
Below Android 8
- Only action is enough for receiving Broadcast
void broadCastParkingStates(Context context) {
Intent intent = new Intent("ReverseCameraStates");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.putExtra("PARKING_GUIDE", ReverseCameraPreference.getParkingGuide(context));
intent.putExtra("PARKING_SENSOR", ReverseCameraPreference.getParkingSensor(context));
intent.putExtra("TRAJECTORY", ReverseCameraPreference.getTrajectory(context));
Log.i("BootCompletedReceiver", "Sending Reverse Camera settings states BaordCast");
Log.i("BootCompletedReceiver", "States Parking:Sensor:Trajectory="
+ intent.getExtras().getBoolean("PARKING_GUIDE")
+ ":" + intent.getExtras().getBoolean("PARKING_SENSOR")
+ ":" + intent.getExtras().getBoolean("TRAJECTORY")
);
context.sendBroadcast(intent);
}