Android - 后台服务在其调用程序 activity 被销毁时停止

Android - Background service stops when its invoker activity is destroyed

我有一个始终 运行 后台服务,在我的 MainActivity 上启动。问题是,当 MainActivity 被销毁时,我的服务会重新启动。这种情况是服务停止的唯一一种情况,因此 "always-running" 运行良好。

我想知道为什么会这样,我能做些什么来防止它。

我的服务没有绑定到我的 activity,因为我不需要它。

服务:

public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener {

    ...
    public LocationService() {

    }

    @Override
    public void onCreate() {

        // Some initialization logic here
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return START_STICKY;
    }

    ...
}

主要活动:

public class MainActivity extends BaseActivity {

    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Start location service in background
        Intent intent = new Intent(this, LocationService.class);
        startService(intent);
    }
}

提前致谢! :D

我猜是因为我没有足够的数据。当您的 MainActivity 被销毁时,托管您的应用程序的 OS 进程中没有活动活动,只有您的 Service。 Android 识别出该进程未托管任何实时活动,因此它会终止该进程以释放资源。由于您的 Service 返回了 START_STICKY,因此 Android 会安排您的 Service 重新启动。 Service 在新的 OS 进程中重新实例化。

您可以在单独的 OS 过程中 运行 您的 Service 来检验这个理论。只需添加

android:process=":remote"

<service> 的清单条目。这可能会对您的申请产生其他影响,因此请确保您了解这一点。

在任何情况下,Android 将随机终止 OS 只承载服务的进程,即使它们返回 START_STICKY。没有任何方法可以防止这种情况发生,尤其是在资源有限的低端设备上。这是Android打扫房间的方式;-)