【发布时间】:2018-07-22 05:55:35
【问题描述】:
我有一个 Android Wear (WearOS) 应用程序在运行 非常长 时间段(比如 1 小时以上)后有时会失去其状态。
我的意思是在长时间运行后,应用程序会从通知中恢复到“状态 A”。
- 状态 A:已停止 - 空闲。
- 状态 B:运行 - 收集 GPS 数据。
但是,如果应用程序运行 20 分钟,它会从通知中正确恢复到“状态 B”。
我的服务等级:
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = this.createNotification();
super.startForeground(PID, notification);
return START_STICKY;
}
private Notification createNotification(){
Log.i("MyService", "createNotification");
Intent mainIntent = new Intent(this, MyActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0, mainIntent,0);
// shortened for breviety ... creates notification ...
return notification;
}
我的活动课:
private void startWatching() {
if(this.intentService != null){
this.stopGpsAndCloseDb();
}
this.intentService = new Intent(this, MyService.class);
this.intentService.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
super.startService(intentService);
}
有人能解释一下这个问题吗,我错过了什么? 谢谢!
【问题讨论】:
-
状态存储在哪里?在每种情况下,您在 logcat 中得到了什么?
-
应用程序不会在任何地方存储其状态,我必须这样做吗?我认为应用程序状态是由 Android 自动管理的。此外,即使使用 logcat 也很难说会发生什么,因为正如我所提到的,问题只是 有时 会发生,而且确实很难重现。谢谢!
-
如果你的应用有它依赖的状态,它负责存储/加载它——操作系统不这样做。重读您的问题...您是说有时当操作系统终止您的进程时,它不会重新启动您的服务?
-
附录:作为开始,我会在存根方法中加入所有
Service生命周期事件的日志记录,以了解当此事件发生时正在发生什么发生。 -
嗨@String,我想你已经搞定了!我相信“活动”正在被杀死,但“服务”仍在继续。这意味着当我点击通知以恢复“活动”时,它会将其恢复为初始状态。您能否提供一个示例,说明我如何将应用程序状态“存储”在“服务”上,以便“活动”返回到正确的状态?非常感谢!
标签: java android wear-os android-wear-2.0