我的一个应用程序有一个后台服务,它使用 onStartCommand
中的 START_STICKY
返回代码在系统终止它时自动重启。
似乎这不再适用于 Android KitKat。
有什么解决方案吗?
我应该在 Kitkat 上做一些不同的事情来保持服务运行吗?
注意:Android-Developers 小组有一个类似的讨论,关于从最近的应用程序列表中滑动应用程序的行为。这两个问题可能相关吗? https://groups.google.com/forum/#!topic/android-developers/H-DSQ4-tiac
编辑:看到 Android 问题跟踪器上存在 Unresolved 错误:
https://code.google.com/p/android/issues/detail?id=63793 https://code.google.com/p/android/issues/detail?id=63618
Edit2:即使服务使用 startForeground
在单独的进程中运行并且在 AndroidManifest.xml 中使用标志 android:stopWithTask="false"
也会发生同样的情况文件...
Edit3:Android 问题跟踪器上的更多相关错误:
https://code.google.com/p/android/issues/detail?id=62091 https://code.google.com/p/android/issues/detail?id=53313 https://code.google.com/p/android/issues/detail?id=104308
是否有某种解决方法来获得以前的行为?
最佳答案
似乎这是 Android 4.4 中存在的一个错误,通过以下方式解决了它:
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI);
}
从 this post 找到这个答案
关于android - START_STICKY 不适用于 Android KitKat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20636330/