Start with this:
int final NOTIFICATION_ID = 1;
//Create an Intent for the BroadcastReceiver
Intent buttonIntent = new Intent(context, ButtonReceiver.class);
buttonIntent.putExtra("notificationId",NOTIFICATION_ID);
//Create the PendingIntent
PendingIntent btPendingIntent = PendingIntent.getBroadcast(context, 0, buttonIntent,0);
//Pass this PendingIntent to addAction method of Intent Builder
NotificationCompat.Builder mb = new NotificationCompat.Builder(getBaseContext());
.....
.....
.....
mb.addAction(R.drawable.ic_Action, "My Action", btPendingIntent);
manager.notify(NOTIFICATION_ID, mb.build());
Create the BroadcastReceiver:
public class ButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId", 0);
// Do what you want were.
..............
..............
// if you want cancel notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notificationId);
}
}
If you don′t want show any activity when user click on notification, define the intent passed in setContentIntent
in this way:
PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
......
......
mb.setContentIntent(resultPendingIntent);
To close notification tray when clicked, call setAutoCancel()
with true when building the notification: mb.setAutoCancel(true);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…