我已经阅读了很多关于这个问题的答案,它们似乎都是一样的:
“使用 START_STICKY 运行您的服务”
“在前台运行您的服务”
“用 startService 运行你的服务,不要绑定(bind)它”
我正在做所有这些事情,但每次我的 Activity 关闭时,我的服务仍然会关闭并重新启动。
这不是 IntentService。 除了在 onClick 处理程序中,我也不会在任何地方调用 stopSelf 或 stopService。
请向下滚动到我的更新 - 此行为已被确认为 android 操作系统中的错误,我已将其报告给谷歌。 Click here to view the report.
从 MainActivity 启动我的服务:
svcIntent = new Intent(getBaseContext(), MyService.class);
startService(svcIntent);
在我的 onStartCommand 中:
// Enter foreground state
String title = "Service has been started...";
String subject = "Service is running...";
String body = "Monitoring your battery usage.";
Notification notification = new Notification(R.drawable.theicon, title,
System.currentTimeMillis());
if (prefs.getBoolean("notificationSounds", true))
notification.defaults |= Notification.DEFAULT_SOUND;
else
notification.sound = null;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, subject, body, pendIntent);
startForeground(1500, notification);
在我的 onStartCommand 结束时:
...
// Release WakeLock
wl.release();
return START_STICKY;
更新
我知道是什么原因造成的!但我不知道如何解决它。在我的服务中,我还在我的服务中使用了一个 AlarmManager 来设置在指定时间间隔内对服务的函数调用。
// Alarm manager setup for MyService
AlarmManager AM = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
svcIntent1 = new Intent(this, AlarmReceiver.class);
prefs.edit().putInt("initialBatt", initialBatt).apply();
svcIntent1.setAction("com.myApp.servicealarm");
pendingIntent = PendingIntent.getBroadcast(this, 93, svcIntent1, PendingIntent.FLAG_UPDATE_CURRENT);
// Set the alarm
AM.set(AlarmManager.RTC_WAKEUP, timeNow + waitTime, pendingIntent);
我注意到,如果我不注释掉用于设置闹钟的 AM.set 调用,即使 onReceive 为空,我的服务也会在闹钟响起时终止,在我在最近的应用程序中滑动我的应用程序之后。如果我注释掉设置的警报调用,则该服务永远不会被终止并在我关闭我的应用程序后继续运行。有没有搞错?!我的算法功能需要这个警报!!
这很奇怪。一旦警报响起,我的调试消息就不会打印出来,我的服务就会重新启动。但是第二次,服务重启后,调试信息打印出来,程序执行成功。
我已经试过了,它仍然会发生在普通的广播接收器上。我还将我的代码精简为仅来 self 的服务和广播接收器的设置警报调用,并且发生了同样的事情,所以这不是我的算法。显然,如果您有设置警报的前台服务,当警报关闭时您的服务会重新启动。
结束
此行为似乎是由 android 操作系统中的错误引起的,因此我不希望得到答案。如果您想亲自查看此错误,click here .我提供了一个项目,您可以使用它来编译和重现问题。
最佳答案
Android 在发送广播 Intent
时终止进程(在您的应用中接收/处理它之前)。
从 4.4 (API 19) 开始,这是一个讨厌的 Android 错误。
特别是评论 #22 和 #23
不幸的是,几乎所有“未解决”的问题最近都被标记为“已过时”,假设它们都已在 Android 5.0 中修复。开发人员无法重新打开“过时”的问题。
编辑:添加有关前台广播的详细信息
根据链接问题中的信息,似乎将 Intent.FLAG_RECEIVER_FOREGROUND
添加到您的广播 Intent
将确保该进程不会在下一次被杀死收到广播 Intent
。
为此,添加:
svcIntent1.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
到您在 AlarmManager
中设置闹钟的代码。
请阅读链接问题中的评论以获取更多详细信息。
关于java - Activity 关闭时服务停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28054942/