onReceive never called in subclass of BroadcastRec

2020-08-04 03:48发布

I'm really new to Android, and I would like to create notifications with a button to cancel. Here is the code:

public class MainActivity extends ActionBarActivity implements OnItemClickListener
{
    ...stuff here...

    void myMethod()
    {
         Intent buttonIntent = new Intent(this,    NotificationButtonReceiver.class);
         buttonIntent.putExtra("notificationId", 8);

         PendingIntent btPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent,0);

         Notification.Builder builder = new Notification.Builder(this)
                .setStyle(new Notification.BigTextStyle().bigText("lorem ipsum dollom"))
                .setAutoCancel(false)
                .setContentTitle("BigText")
                .setContentText("Hello from BigText")
                .setSmallIcon(R.drawable.like)
                .addAction(R.drawable.abc_btn_radio_material, "Dismiss", btPendingIntent);

         Notification notif = builder.build();
         NotificationManager manager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);

         manager.notify(8, notif);
    }

    ...stuff here...
}

public class NotificationButtonReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) {

        int notificationId = intent.getIntExtra("notificationId", 0);

        Toast.makeText(context.getApplicationContext(), "received",
                Toast.LENGTH_SHORT).show();

        NotificationManager manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        manager.cancel(notificationId);
    }
}

The method called myMethod is successfully called, but never the method onReceive despite I click on the button dismiss.

Any suggestions?

1条回答
Evening l夕情丶
2楼-- · 2020-08-04 04:31

As you are using BroadCastReceiver you need to register (@Harsh mentioned).

Here what you need to do

Add below code in manifest's application tag

    <receiver android:name="your.package.name.NotificationButtonReceiver">
        <intent-filter>
            <action android:name="notify_dismiss" />
        </intent-filter>
    </receiver>

PendingIntent stuff

    Intent buttonIntent = new Intent("notify_dismiss");
    buttonIntent.putExtra("notificationId", 8);

    PendingIntent btPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent,0);
查看更多
登录 后发表回答