如何在Android上运行无限服务(前台服务被杀死)?

Oha*_*dos 4 android android-service

我创建了一个粘性前台服务,每次它被杀死时都会重新启动,它似乎工作正常,但我注意到在某些情况下(当操作系统杀死它时)它不会重新启动。我怎样才能让它在每次被杀死时重新启动?我希望这项服务始终运行。

我希望它像那些一样运行

喜欢那些服务。

这是我的前台服务 onStartCommand:

public int onStartCommand(Intent intent, int flags, int startId) {

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("InsiteMobile Service")
            .setContentText("Run the app by clicking here")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pendingIntent)
            .build();
    Log.i("InsiteMobileLog", "Service Started");
    startForeground(1, notification);

    //do heavy work on a background thread
    //stopSelf();

    return START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)

这就是我在 MainActivity onCreate() 中调用服务的方式:

public void startService() {

    Intent serviceIntent = new Intent(this, AppService.class);
    serviceIntent.putExtra("inputExtra", "InsiteMobileService");

    ContextCompat.startForegroundService(this, serviceIntent);
}
Run Code Online (Sandbox Code Playgroud)

Abh*_*jit 5

目前我正在开发同一个项目,我需要在后台运行服务。有几件事我们需要关心
1. 在服务的onDestroy()方法中,使用startService Intent再次启动自身
2. 对于带有及以下 kitkat 的操作系统,使用onTaskRemoved(intent); onStartCommand()方法中
3.在onStartCommand()中返回START_STICKY

之后,您还需要了解一件事,设备的电话管理器往往会根据电池优化策略杀死后台进程。检查测试设备的手机管理器设置,然后重试。

此外,如果您要使用通知来保持服务处于活动状态,则需要重新检查通过应用程序发送通知的权限。

  • 你能再解释一下第二点吗?我不明白。您能更具体地介绍一下电话管理器的事情吗? (2认同)