首页 > 解决方案 > 无法“重新绑定”到同一服务

问题描述

我正在构建一个计时器应用程序。计时器在服务上运行并更新 ui。应用程序在 onCreate() 中启动服务。

getApplication().startService(intentService);
getApplication().bindService(intentService, serviceConnection, Context.BIND_AUTO_CREATE);

有用。除非它没有。特别是关于配置更改。

我知道调用活动被破坏(onDestroy)然后重新创建,再次调用 onCreate 并且... bindService()应该绑定到同一个服务。我在相同的(应用程序)上下文中使用相同的 Intent、相同的 serviceConnection 调用它。

它没有。它以某种方式绑定到一个新的服务对象。(我在调试器中可以看到,返回给activity的对象不一样)。这打破了我的计时器。

有趣的是,当我退出活动并通过通知重新进入活动时(它是一个前台服务,通知将您带到同一个活动), onCreate() 再次被调用,startService 和 bindService 也被调用,但是那个时候,它是以某种方式能够正确绑定到正在运行的服务。

我错过了什么?

编辑:以下是服务代码的主要部分:

public class MyService extends IntentService {
    // variables ...
    public MyService() { super("MyService"); }
    protected void onHandleIntent(@Nullable Intent intent) {
         if (!hasStarted) {
              initializeTimer();
              startTimer();
         }
    }

    public IBinder onBind(Intent intent) {
         return new RecordBinder(this);
    }

    public void onDestroy() {
          super.onDestroy();
          if (timer != null)
              timer = null;
    }
    // there are also a bunch of private methods and stuff...
}

标签: javaandroidandroid-activityservicebindservice

解决方案


推荐阅读