Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android UI Update Thread - saving and restoring it

How do I properly do that?

I have a stopwatch and I'm saving it's state in onSaveInstance and restoring it's state in onRestoreInstance...

Now I've following problem: if I stop the thread in onSaveInstance and the screen get's locked or turned off, onRestoreInstance is not called and the stopwatch is not continuing...
If I don't stop it, the stopwatch is running in background on and on even when the screen is off or the activity is not active anymore...

So what's the usual way to handle such a thing?

PS:
I even have a working solution, a local variable to save the running state in the onStop event and restarting the thread in the onStart event... But I still want to know if there's a "default" solution using the android system itself....

like image 440
prom85 Avatar asked Jan 17 '13 11:01

prom85


1 Answers

Ok. I better now understand what you're doing. I thought you were using the thread to count. Right now it sounds like you're using it to update the UI.

Instead, what you probably should be doing is using a self-calling Handler. Handlers are nifty little classes that can run asynchronously. They're used all over the place in Android because of their diversity.

static final int UPDATE_INTERVAL = 1000; // in milliseconds. Will update every 1 second

Handler clockHander = new Handler();

Runnable UpdateClock extends Runnable {
   View clock;

   public UpdateClock(View clock) {
      // Do what you need to update the clock
      clock.invalidate(); // tell the clock to redraw.
      clockHandler.postDelayed(this, UPDATE_INTERVAL); // call the handler again
   }
}

UpdateClock runnableInstance;

public void start() {
   // start the countdown
   clockHandler.post(this); // tell the handler to update
}

@Override
public void onCreate(Bundle icicle) {
   // create your UI including the clock view
   View myClockView = getClockView(); // custom method. Just need to get the view and pass it to the runnable.
   runnableInstance = new UpdateClock(myClockView);
}

@Override
public void onPause() {
   clockHandler.removeCallbacksAndMessages(null); // removes all messages from the handler. I.E. stops it
}

What this will do is post messages to the Handler which will run. It posts every 1 second in this case. There is a slight delay because Handlers are message queues that run when available. They also run on the thread that they're created on, so if you create it on the UI thread you will be able to update the UI without any fancy tricks. You remove the messages in the onPause() to stop updating the UI. The clock can continue to run in the background, but you won't be showing it to the user anymore.

like image 67
DeeV Avatar answered Oct 28 '22 19:10

DeeV