@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
final Intent intent = new Intent(MainActivity.this, AlertActivity.class);
final PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setContentText("Click here");
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle(getString(R.string.app_name));
builder.addAction(R.mipmap.ic_launcher, "Test", pendingIntent);
builder.setAutoCancel(true);
NotificationManagerCompat.from(MainActivity.this).notify(0, builder.build());
}
});
}
我还通过删除builder.addAction()进行了实验,但是当我点击通知时无效。如果在不添加操作的情况下单击通知,我们如何引导用户访问特定活动?另外,在任何一种情况下;除非我手动滑动删除通知,否则我无法解除通知。
答案 0 :(得分:8)
autoCancel仅在调用默认通知单击时才会起作用,如果您使用的按钮必须清除自己的通知
在您的NotificationManager实例上调用clear(int id),您的案例id为0
答案 1 :(得分:3)
使用setContentIntent
可以解决您的问题:
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
完整代码:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setContentText("Click here");
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle(getString(R.string.app_name));
builder.setAutoCancel(true)
builder.addAction(R.mipmap.ic_launcher, "Test", pendingIntent);
builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
});
更新:
builder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;