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

喜欢那些服务。
这是我的前台服务 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)