服务在短时间(1 分钟)后被终止

Service is killed after a short period of time (1 minute)

我创建了一项服务,它的工作是在用户关闭应用程序时清除通知。一切都运行良好,但 有时,当应用程序在后台运行超过 1 分钟时,服务会被终止 (这意味着通知不会被取消)。 为什么会这样?我认为停止服务的唯一方法是使用 stopSelf() 或 stopService()。

public class OnClearFromRecentService extends Service {
    private static final String TAG = "onClearFromRecentServic";
    private NotificationManagerCompat mNotificationManagerCompat;

    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service Started");
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service Destroyed");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        //Put code here which will be executed when app is closed from user.
        Log.d(TAG, "onTaskRemoved was executed ");
        if (mNotificationManagerCompat != null) {
            mNotificationManagerCompat.cancelAll();
        } else {
            Log.d(TAG, "onTaskRemoved: mNotifManager is null!");
        }

        stopSelf();
    }
}

我从初始屏幕 Activity 启动服务,如下所示:startService(new Intent(this, OnClearFromRecentService.class));

这里还有一些日志消息:

尝试从 onStartCommand 返回 START_STICKY
然后系统会尝试重新创建。
查看 this 官方文档。

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service Started");
        return START_NOT_STICKY;
    }

如果您还希望重新传送 Intent,您也可以尝试返回 START_REDELIVER_INTENT。

START_REDELIVER_INTENT

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int).

来自文档。

我在@emandt 的帮助下找到了解决方案。

我刚刚在 onStartCommand() 中添加了这些代码行:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "Service Started");
    Notification notification = new NotificationCompat.Builder(this, CHANNELID)
            .setContentTitle("title")
            .setContentText("text")
            .setSmallIcon(R.drawable.baseline_pause_white_24)
            .build();
    startForeground(2001,notification);
    return START_NOT_STICKY;
}

根据文档,startForeground 方法:

If your service is started then also make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state...By default started services are background, meaning that their process won't be given foreground CPU scheduling (unless something else in that process is foreground)

此外,

If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground. If an app needs to create a foreground service, the app should call startForegroundService(). That method creates a background service, but the method signals to the system that the service will promote itself to the foreground. Once the service has been created, the service must call its startForeground() method within five seconds.