android Notification doesnt trigger BroadcastReceiver's onReceive
From your code...
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
When creating a PendingIntent
targetting a BroadcastReceiver
, you have to use getBroadcast(...)
and not getActivity(...)
.
See PendingIntent.getBroadcast(Context context, int requestCode, Intent intent, int flags)
Also, don't create your Intent
like this...
Intent notificationIntent = new Intent(context,MyBroadcastReceiver.class);
That is an explicit Intent
which targets a specific class (used for starting a specific Activity
class usually).
Instead create a 'broadcast' Intent
with an 'action' such as...
Intent notificationIntent = new Intent(MyApp.ACTION_DO_SOMETHING);
You'll also need to specify a <intent-filter>
section for the <receiver android:name=".MyBroadcastReceiver" />
section of your manifest.
Abhishek
Master student at Georgia Tech. Android Developer. Interest in User Experience. Weekly online programming competitions. Entrepreneur.
Updated on July 09, 2022Comments
-
Abhishek almost 2 years
Is it possible to have a notification start a broadcast receiver?
I tried this code but it doesnt work.
Notification is created but when I click on it nothing happens.
NOTE: When I change the notificationIntent to point from MyBroadcastReceiver.class to an activity (like MainActivity.class) it works fine.
Notification creation:
NotificationManager notificationManager = (NotificationManager) context.getSystemService( Context.NOTIFICATION_SERVICE); int notificationIconId = XXXXXX Notification notification = new Notification( notificationIconId, XXXXXX, System.currentTimeMillis() ); CharSequence contentTitle = XXXXXXX CharSequence contentText = XXXXXX Intent notificationIntent = new Intent(context,MyBroadcastReceiver.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); notificationManager.notify(1,notification);
Here is the BroadcastReceiver
public static class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { /* */ } }
Inside AndroidManifest.xml
<receiver android:name=".MyBroadcastReceiver" />