【发布时间】:2019-06-21 22:56:17
【问题描述】:
我创建了一个粘性前台服务,每次它被杀死时都会重新启动,它似乎工作正常,但我注意到在某些情况下(当操作系统杀死它时)它不会重新启动。每次它被杀死时,我怎样才能让它重新启动?我希望此服务始终运行。
喜欢那些服务。
这是我的前台服务 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);
}
【问题讨论】:
-
幸运的是你不能这样做 - 我真的不希望有一个“不朽”的恶意服务
-
为什么我不能,而 WhatsApp、Facebook 和所有这些都可以?顺便说一句,它是一个私人应用程序供个人使用,这就是我需要的。
-
它是否用于个人用途并不重要:禁止此类服务 - 如果您需要“长期”服务,请在前台启动它们(
Service#startForeground()方法) -
我写道我确实使用了 startForeground()。但在某些情况下,此服务会被操作系统杀死,在这种情况下不会重新启动。
-
你能显示你的前台代码吗?前台服务不是操作系统在资源不足时终止的候选者。