Android UI Update - Saving and Restoring

How to do it right?

I have a stopwatch and I save it in onSaveInstance and restore its state to onRestoreInstance ...

Now I have a problem: if I stopped the stream in onSaveInstance and the screen is locked or turned off, onRestoreInstance not called and the stopwatch does not continue ...
If I do not stop it, the stopwatch will run in the background on. And on, even if the screen is off or the activity is no longer active ...

So what is the usual way to handle such a thing?

PS:
I even have a working solution, a local variable, to save the current state in the onStop event and restart the stream in the onStart event ... But I still want to know if there is a "standard" solution using the android of the system itself ....

+6
source share
2 answers

Ok Now I better understand what you are doing. I thought you were using a thread to count. Now it sounds like you are using it to update the user interface.

Instead of what you should probably do, use a self-call Handler . Handler are great little classes that can execute asynchronously. They are used universally 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. IE stops it } 

What this will do is send messages to Handler that will be executed. In this case, it is placed every 1 second. There is a slight delay because Handlers are message queues that start when they are available. They also run in the thread on which they are created, so if you create it in the user interface thread, you can update the interface without any fancy tricks. You delete messages in onPause() to stop updating the user interface. The watch may continue to run in the background, but you will no longer show it to the user.

+2
source

I just got into Android programming, but I do not think that onRestoreInstance will be called in this situation, because you are not switching from one action to another. I think it's best to call onPause , which then will call onSaveInstance if you need it, but use onResume , which might or might not call onRestoreInstance .

0
source

All Articles