我试图制作一个粘性服务,它会在死后很短的时间后重新启动(例如,因为Android已杀死它以释放内存)。 (联合国)幸运的是我在Android 5.0.1上有一个漂亮的内存泄漏错误,可以轻松实现真正的测试。
看logcat
我看到了:
I/ActivityManager( 943): Process com.app.my (pid 28834) has died
W/ActivityManager( 943): Scheduling restart of crashed service com.app.my/com.service.my in 191688ms
I/ActivityManager( 943): Process com.app.my (pid 30842) has died
W/ActivityManager( 943): Scheduling restart of crashed service com.app.my/com.service.my in 766752ms
后来时间增加到3M使其无法接受。
我尝试使用AlarmManager修复此问题并重启意图:
Intent restartIntent = new Intent(activity, activity.getClass());
restartIntent.putExtra("config", config);
PendingIntent restartAct = PendingIntent.getActivity(
activity.getApplicationContext(), 0, restartIntent, PendingIntent.FLAG_NO_CREATE);
AlarmManager alarmManager = (AlarmManager)activity.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 60000, 60000, restartAct);
然而这并没有帮助。我无法在日志中找到任何信息,因此可能在活动已经死亡或者我做错了事情之后放弃了AlarmManager重复?
我正在观察WhatsApp应用程序,我发现:
I/ActivityManager( 943): Process com.whatsapp (pid 27009) has died
W/ActivityManager( 943): Scheduling restart of crashed service com.whatsapp/.messaging.MessageService in 10947ms
I/ActivityManager( 943): Process com.whatsapp (pid 29913) has died
W/ActivityManager( 943): Scheduling restart of crashed service com.whatsapp/.messaging.MessageService in 10918ms
I/ActivityManager( 943): Process com.whatsapp (pid 30681) has died
W/ActivityManager( 943): Scheduling restart of crashed service com.whatsapp/.messaging.MessageService in 10987ms
第一次和最后一次崩溃与com.app.my进程完全同时发生。不知怎的,WhatsApp设法保持"重试时间"尽管频繁崩溃,但处于同一水平。他们是如何做到的?这里的答案表明它对于所有aps应该是相同的:Crashed service restarted after a very long time
说明:
答案 0 :(得分:1)
检查:
Intent watchdogIntent = new Intent(getApplicationContext(), SomeClasss.class);
watchdogIntent.setAction(INTENT_ACTION);
((AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE))
.setInexactRepeating(
AlarmManager.ELAPSED_REALTIME,
0,
currentWatchDogInterval,
PendingIntent.getService(
getApplicationContext(),
0,
watchdogIntent,
0)
);