Java 单击“操作”按钮后无法取消通知
所以我得到了这个代码来构建通知。我试图在单击操作按钮后取消通知。但这段代码并没有做到这一点。为什么?Java 单击“操作”按钮后无法取消通知,java,android,notifications,Java,Android,Notifications,所以我得到了这个代码来构建通知。我试图在单击操作按钮后取消通知。但这段代码并没有做到这一点。为什么? Intent intentAction = new Intent(this, ActionReceiver.class); PendingIntent pIntentlogin = PendingIntent.getBroadcast(this,1,intentAction,PendingIntent.FLAG_CANCEL_CURRENT); Notification
Intent intentAction = new Intent(this, ActionReceiver.class);
PendingIntent pIntentlogin = PendingIntent.getBroadcast(this,1,intentAction,PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Program running...")
.setSmallIcon(R.drawable.edit_location)
//.setContentIntent(pendingIntent)
.addAction(R.drawable.edit_location, "TURN OFF", pIntentlogin)
.build();
startForeground(1, notification);
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);
这个ActionReceiver类:
public class ActionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ExampleService.doTask();
//This is used to close the notification tray
Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(it);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(1);
}
}
这是因为据我所知,您的通知代表前台服务。要关闭此类通知,您应该关闭服务(Context.stopService或stopSelf on service本身),并且您的通知将自动关闭。这是因为我所理解的您的通知代表前台服务。要关闭此类通知,您应该终止服务(Context.stopService或服务本身上的stopSelf),并且您的通知将自动关闭。