【问题标题】:Started and Bound service is mysteriously stopped and restartedStarted and Bound 服务神秘地停止并重新启动
【发布时间】:2014-06-13 03:03:14
【问题描述】:

我的活动尝试启动并绑定一个应该独立运行的服务。此服务打开 GPS。

onCreate 调用 getApplicationContext.StartService,而 onResume 调用 getApplicationContext.BindService。 OnPause 调用getApplicationContext.unbindService,尽管它似乎从未正常运行(服务连接从未记录取消绑定,尽管在我以类似方式处理绑定时会记录绑定)。

不幸的是,当我打开我的“最近”列表并将活动滑开时,服务会停止,然后几乎立即重新启动,从而断开 GPS 连接。什么会导致这种行为?

@Override
protected void onStart() {
    super.onStart();
}

@Override
protected void onResume() {
    super.onResume();

    // Start up the service
    Intent intent = new Intent(getApplicationContext(), LockService.class);
    getApplicationContext().bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onPause() {
    super.onPause();
    Log.i(tag, "onPause");
    if (isBound) {
        getApplicationContext().unbindService(myConnection);
    }
}

...

// Bound service stuff
    LockService myService;
    boolean isBound = false;

    private ServiceConnection myConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        LockBinder binder = (LockBinder) service;
        myService = binder.getService();
        isBound = true;

        final boolean status = myService.getStatus();
        Log.i(tag, "service bound");
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        isBound = false;
        Log.i(tag, "service unbound");
    }
};

编辑:我检查了这个答案,但这只是阻止服务立即重新启动(它仍然挂起,重新打开活动会重新初始化它):

Android onCreate Service called when Activity onDestroy called

编辑 2: 我对这个答案的希望有点过头了。它似乎也无法解决任何问题。

How to force the onServiceDisconnected() get called?

编辑 3:这可能是奇巧的东西。

In android 4.4, swiping app out of recent tasks permanently kills application with its service . Any idea why?

【问题讨论】:

    标签: android android-service


    【解决方案1】:

    由于在 Android 4.4 (KK) 版本中将应用从“最近”列表中滑出会杀死它,因此我选择根本不在“最近”列表中显示我的应用。

    哦,好吧,反正它真的不需要住在那里。它在通知栏中非常愉快地存在。我很同情那些没有那么幸运的人,需要通过计时器和一些陈旧的代码来强制重启服务。

    【讨论】: