【问题标题】:Android Service Closes After UnbindAndroid服务在解除绑定后关闭
【发布时间】:2015-10-21 19:38:21
【问题描述】:

我有一个需要从活动中获取一些输入的服务。为了让他们交流,我将活动绑定到我的服务,并且交流效果很好。但是,一旦活动关闭并与服务解除绑定,服务也会停止。 是否可以在不杀死服务的情况下解绑?

这就是我启动服务并绑定它的方式:

Intent serviceIntent = new Intent(this, MyService.class);
//Add user preferences to the service
serviceIntent.putExtra("panel", tbtnBar.isChecked());
serviceIntent.putExtra("sensor", tbtnDown.isChecked());
//Start the service
startService(serviceIntent);

//Bind the service
 isBound= bindService(serviceIntent, mConnection,0);

服务在 onDestroy 中未绑定:

 @Override
    public void onDestroy()
    {
        if(isBound)
            unbindService(mConnection);

        super.onDestroy();
    }

我四处搜索,所有帖子都只是说在绑定之前启动服务而不使用 BIND_AUTO_CREATE 标志。我似乎正在这样做。

【问题讨论】:

  • “但是,一旦活动关闭并与服务解除绑定,服务也会停止”——您如何确定这一点?
  • 当它运行时,我会弹出一个鲜红色的窗口,告诉我它已打开。当服务关闭时,窗口消失。
  • 你在哪里添加和删除服务中的“亮红色窗口弹出”?
  • 在 onStartCommand() 中添加窗口,在 onDestroy() 中删除它
  • 我还使用“实时 CPU”运行看门狗应用程序以查看哪些服务正在运行。当 Activity 被销毁时服务停止。

标签: java android android-service android-service-binding


【解决方案1】:

看!这很棘手。 例如,我们说一个服务可以通过调用 startService(intent)bindService(intent,serviceConnection,BIND_AUTO_CREATE) 来启动。

通过bindService启动服务时,onCreate之后并没有调用该服务的onStartCommand,实际上是调用了onBind

由 bindService(intent,serviceConnection,BIND_AUTO_CREATE) 启动的服务在绑定到它的活动被销毁后立即被销毁。

但是当我们从 startService(intent) 启动服务时,onStartCommand 会在 oncreate 之后触发,我们可以从该方法返回 start_sticky。 在这种情况下,除非系统这样做,否则服务将永远不会被销毁,而不管服务连接绑定和解除绑定。该服务将保留在那里。

【讨论】:

    猜你喜欢
    • 2015-09-11
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    相关资源
    最近更新 更多