我有一个 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;
}
我的 Activity 类:
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);
}
有人可以阐明这个问题吗,我错过了什么? 谢谢!
最佳答案
在我的例子中,下面的代码起到了作用(经过测试/已经在生产中)。
Activity - SINGLE_TOP:
this.intentService = new Intent(this, MyService.class);
this.intentService.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
服务 - START_STICKY & SINGLE_TOP & Action & Category:
Intent mainIntent = new Intent(this, MyActivity.class);
mainIntent.setAction(Intent.ACTION_MAIN);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mainIntent, 0);
AndroidManifest.xml - launchMode="singleTop":
<activity
android:name=".MyActivity"
android:label="@string/app_name"
android:launchMode="singleTop">
我要感谢@String 为我指明了正确的方向。
关于java - Android Wear - 长时间运行的应用程序丢失状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51462425/