【问题标题】:How to block restarting service when app closed on android?当应用程序在android上关闭时如何阻止重新启动服务?
【发布时间】:2014-10-12 23:07:39
【问题描述】:

应用程序和后台服务一起运行。但是当应用程序关闭时,后台服务正在重新启动?
为什么?如何阻止此重启?

当应用程序关闭时,服务应该继续 什么都没发生。我该怎么做?



我在 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。

【问题讨论】:

  • 操作系统可以在需要一些内存时随时停止您的服务。因此,最好提供不受任何这些问题影响的服务

标签: android android-intent android-activity android-service android-background


【解决方案1】:

服务和活动是否在同一个进程上运行?如果是这样,那么这可能就是您的服务行为如此的原因(如果两者共享相同的进程,那么当应用程序死亡时进程也会死亡,如果它使用 START_STICKY 会导致服务自行重启)......也许您应该尝试运行该服务在一个单独的过程中..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多