Search code examples
androidandroid-intentbroadcastreceiverandroid-notificationsandroid-pendingintent

BroadcastReceiver not receiving when .addAction() is pressed


I'm trying to dismiss a notification from an .addAction() without having to open the app. The problem is when the button is pressed nothing happens, the onReceive() method doesn't trigger.

Here is the code on the MainActivity:

 Intent notificationIntent = new Intent(mContext, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notificationIntent.putExtra("id", SOMENUMBER);
    PendingIntent pIntent = PendingIntent.getBroadcast(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder notification = new NotificationCompat.Builder(mContext);
    notification.setContentTitle("");
    notification.setContentText(t);
    notification.setSmallIcon(R.mipmap.ic_launcher);
    notification.setOngoing(true);
    notification.addAction(R.mipmap.ic_launcher, "Dismiss", pIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(SOMENUMBER, notification.build());

And on other class I have the reciever:

public class Notification extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent){
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(intent.getIntExtra("id", 0));
    }
}

And the reciever on the AndroidManifest.xml file:

<receiver android:name=".MainActivity">
    <intent-filter>
        <action android:name="io.github.seik.Notification" />
    </intent-filter>
</receiver>

Solution

  • Your naming conventions are confusing. Android already has a class called Notification, so you probably shouldn't call your receiver Notification :-(

    If MainActivity extends Activity then you need to have a manifest entry for it that looks like this:

    <activity android:name=".MainActivity"/>
    

    For your BroadcastReceiver, you need a manifest entry like this:

    <receiver android:name=".Notification"
        android:exported="true"/>
    

    Since you are using an explicit Intent to launch your BroadcastReceiver, you don't need to provide an <intent-filter> for it. Since the BroadcastReceiver will be started by the NotificationManager, you need to make sure that it is exported.

    You then need to create the PendingIntent so that it actually launches your BroadcastReceiver, so change this:

    Intent notificationIntent = new Intent(mContext, MainActivity.class);
    

    to this:

    Intent notificationIntent = new Intent(mContext, Notification.class);