我创建了一个黏性前台服务,每次它被杀死时都会重新启动,看起来它运行得很好,但我注意到在某些情况下(例如当操作系统将其杀死时),它就不会重新启动。如何让它在每次被杀死时都重新启动?我希望这个服务始终运行。
就像那些服务一样。
以下是我的前台服务 onStartCommand:
![I want it to run like those](https://istack.dev59.com/wBuQj.webp)
以下是我的前台服务 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;
}
这是我在MainActivity onCreate()中调用服务的方式:
public void startService() {
Intent serviceIntent = new Intent(this, AppService.class);
serviceIntent.putExtra("inputExtra", "InsiteMobileService");
ContextCompat.startForegroundService(this, serviceIntent);
}
public void startService() { Intent serviceIntent = new Intent(this, AppService.class); serviceIntent.putExtra("inputExtra", "InsiteMobileService"); ContextCompat.startForegroundService(this, serviceIntent); }
并且我在onStartCommand()中使用startForeground()并返回START_STICKY。 - Ohados