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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.