如果我按下“全部清除”按钮,为什么我的前台服务会停止

问题描述

我在清单中的许可

使用权限 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();

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...