java - 无法“重新绑定”到同一服务
问题描述
我正在构建一个计时器应用程序。计时器在服务上运行并更新 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...
}
解决方案
推荐阅读
- node.js - 如何测试调用或不使用 mocha & chai 与 sinon TDD 的类?
- c++ - 非重叠领域的代码效率不够
- python - Pandas groupby & 转置数据帧,同时保留原始列
- swiftui - 从 SwiftUI 工具栏中关闭当前视图将我带到根视图
- ip - 在笔记本电脑和 PC 上运行 nmap 时获取不同的 MAC 地址
- python - 将每日股票价格变成每周/每月/每季度/学期/每年?
- mysql - 当我在 where 子句中每行只有一个唯一变量时,如何返回多行?
- r - R,从向量中查找字符串,创建新的 TRUE/FALSE 列
- python - 如何在 CPU 上的 pyopencl 和 numpy 之间桥接数组?
- django - Django复选框不返回任何内容