使用 NotificationCompat .addAction 按钮停止前台服务
Stopping Foreground service using NotificationCompat .addAction button
如何使用它在 class 中创建的通知来停止前台服务?
Intent stopnotificationIntent = new Intent(this, HelloIntentService.class);
//Not sure which is the current action to set
stopnotificationIntent.setAction("ACTION.STOPFOREGROUND_ACTION");
PendingIntent pIntent = PendingIntent.getService(this, 0, stopnotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.addAction(0, "Cancel", pIntent);
startForeground(1111, notificationBuilder.build());
按钮是从 .addAction
创建的,我想停止当前的前台服务
String ACTION_STOP_SERVICE= "STOP";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (ACTION_STOP_SERVICE.equals(intent.getAction())) {
Log.d(Statics.LOG_TAG,"called to cancel service");
stopSelf();
}
Intent stopSelf = new Intent(this, HelloIntentService.class);
stopSelf.setAction(ACTION_STOP_SERVICE);
PendingIntent pStopSelf = PendingIntent
.getService(this, 0, stopSelf
,PendingIntent.FLAG_CANCEL_CURRENT); // That you should change this part in your code
notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentText("Bla Bla Bla")
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingNotificationIntent)
.addAction(R.drawable.xxxx,"Close", pStopSelf)
.setSound(null)
.build();
startForeground(REQUEST_CODE, notification);
}
如何使用它在 class 中创建的通知来停止前台服务?
Intent stopnotificationIntent = new Intent(this, HelloIntentService.class);
//Not sure which is the current action to set
stopnotificationIntent.setAction("ACTION.STOPFOREGROUND_ACTION");
PendingIntent pIntent = PendingIntent.getService(this, 0, stopnotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.addAction(0, "Cancel", pIntent);
startForeground(1111, notificationBuilder.build());
按钮是从 .addAction
创建的,我想停止当前的前台服务
String ACTION_STOP_SERVICE= "STOP";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (ACTION_STOP_SERVICE.equals(intent.getAction())) {
Log.d(Statics.LOG_TAG,"called to cancel service");
stopSelf();
}
Intent stopSelf = new Intent(this, HelloIntentService.class);
stopSelf.setAction(ACTION_STOP_SERVICE);
PendingIntent pStopSelf = PendingIntent
.getService(this, 0, stopSelf
,PendingIntent.FLAG_CANCEL_CURRENT); // That you should change this part in your code
notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentText("Bla Bla Bla")
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingNotificationIntent)
.addAction(R.drawable.xxxx,"Close", pStopSelf)
.setSound(null)
.build();
startForeground(REQUEST_CODE, notification);
}