Changing the Android system clock stops the timers. How can I restart them?

I need to run a periodic task in an android app. I am currently using a timer like this:

final Handler guiHandler = new Handler(); // the task to run final Runnable myRunnable = new Runnable() { @Override public void run() { doMyStuff(); } }; Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { guiHandler.post(myRunnable); } }, 0, 30000); // run every 30 seconds 

This does exactly what I need, but there is a problem: if I change the time on the emulator or phone, the timer stops working. This is what appears in the log when I change the time:

 D/SystemClock( 331): Setting time of day to sec=1278920137 W/SystemClock( 331): Unable to set rtc to 1278920137: Invalid argument 

Nothing about interrupting the timer, but it obviously does not start after changing the system clock. I need the task to go on all the time while the application is running.

How to restart the timer if it is stopped like that? There is no method on Timer or TimerTask to check if it is currently running, so I cannot know when to migrate it. Any ideas?

+7
android timer systemtime
source share
1 answer

I think there are several ways to do this. I would not use a timer anyway.

You can use a handler to run your task when calling postDelayed. Then your task was to re-register using the handler from the inside.

 final int ONE_SECOND = 1000; // one second final Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { ... // do some stuff if (expression) { handler.postDelayed(this, ONE_SECOND); } } }, ONE_SECOND); 

This will cause the task to run during your application. You can also configure delayed speed in postDelayed in Runnable. This path is semi-predictable while you make another Looper. Using the main thread may or may not be appropriate depending on the task.

There is also an AlarmManager, which you can access through the Context interface, which is designed to perform repetitive tasks at more precise intervals. It's a little harder to use, but you get the flexibility to use RTC and keep repetitive tasks.

 AlarmManager manager = mContext.getSystemService(Context.ALARM_SERVICE); manager.setRepeating(AlarmManager.RTC, <start_time_millis>, <period_millis>, pendingIntent); 

For example, a pending intent can trigger a broadcast intent that you can listen to elsewhere. You can create this pendingintent in onCreate of your custom application object and cancel the intent in onTerminate ().

+3
source share

All Articles