问题描述
我在清单中的许可
使用权限 android:name="android.permission.FOREGROUND_SERVICE"
服务是
android:stopWithTask="false"
onStartCommand 返回 START_STICKY 并创建此代码的通知
private void startForegroundService() {
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this,notificationIntent,0);
Notification notification = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notification = new Notification.Builder(this,"SEX")
.setContentTitle("getText(R.string.notification_title)")
.setContentText("getText(R.string.notification_message)")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent)
.setTicker("ssss")
.build();
}else {
notification = new Notification.Builder(this)
.setContentTitle("getText(R.string.notification_title)")
.setContentText("getText(R.string.notification_message)")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent)
.setTicker("ssss")
.build();
}
startForeground(423,notification);
}
但是如果我按下“全部清除”按钮,我的服务在没有调用 onTaskRemoved 的情况下就死了
解决方法
您需要的是一个 ongoing notification,将其设置在您的 Notification.Builder
对象上:
notification = ...
...
.setOngoing(true)
.build();