Search code examples
javaandroidwear-osandroid-wear-2.0

Android Wear - Long Running App loses state


I have an Android Wear (WearOS) app that after running for a very long period of time ( say 1 hour plus ) sometimes loses its state.

By losing its state I mean after a long time running the app resumes in "State A" from its notification.

  • State A: Stopped - idle.
  • State B: Running - collecting GPS data.

However, if the app runs for let's say 20 mins it resumes rightly in "State B" from its notification.


My Service Class:

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;
}

My Activity Class:

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);
}

Could someone shed some light into this problem, what am I missing? Thanks!


Solution

  • In my case, the following below did the trick ( tested / already in production ).

    Activity - SINGLE_TOP :

    this.intentService = new Intent(this, MyService.class);
    this.intentService.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    

    Service - 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">
    

    I would like to thank @String for pointing me in the right direction.