android - 如何在应用程序在 Android 上关闭时阻止重新启动服务?

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

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

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/

相关文章:

android - 使用 setOnClickFillInIntent 和 setPendingIntentTemplate 时,不会发生点击事件

java - 如何将搜索 View 移动到屏幕左侧?

android - 使用 Android Intent 发送基于 HTML 的电子邮件正文

Android:在 Android 生命周期中保存状态

android - getExtras() 在应用程序级别(-class)返回 null

android - 以编程方式从 Activity/服务/接收器更新小部件

如果使用 FLAG_NO_CLEAR,则不会显示 Android Wear Notification

java - Activity.getIntent() 可以返回 null 吗?

android - 在 Android 中处理未知的 URI 方案(比特币示例)

java - 在android studio 2.1中导入http包时出错