应用程序和后台服务一起运行。但是当应用程序关闭时,后台服务正在重新启动?
为什么?我该如何阻止此重启?
When the application is closed, the service should continue like nothing happened.How can I do that?
我在 MainActivity 中使用此代码:
tryConnect();
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private void tryConnect(){
if(!isMyServiceRunning(BackService.class)){
startService(new Intent(this,BackService.class));
}
}
后台服务返回START_STICKY;(我尝试了START_NOT_STICKY、START_REDELIVER_INTENT,但没有用)
我在 Android 应用程序中没有 onDestroy。
最佳答案
服务和 Activity 是否在同一个进程上运行?如果是这样,那么这可能就是您的服务表现如此的原因(如果两者共享相同的进程,那么当应用程序死于处理时,如果它使用 START_STICKY 也会导致服务自行重启)...也许您应该尝试运行该服务在一个单独的过程中..
关于android - 如何在应用程序在 Android 上关闭时阻止重新启动服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25390363/