Resuming CountdownTimer after rotation

只愿长相守 提交于 2019-12-07 03:01:28
user1449018

I would give your timer it's own thread. Your timer is being stopped because it's on the UI thread (as you stated) and when the UI redraws the Activity is re-initialized. All long running processes should have their own thread. Rule of thumb: get out of the UI thread as soon as possible.

Here is an example of using a Service. This service will start when called and stay in memory regardless of screen orientation changes or even activity focus changes.

Here is the service:

public class Timer extends Service {

    @Override
    public IBinder onBind(Intent i) {
        return null;
    }
    @Override
    public int onStartCommand(Intent i, int flags, int startId) {
        // Put your timer code here
    }
}

You will need to add this line to your manifest (somewhere between the application open/close tags):

<service android:name=".Timer" />

Then you can start the service at any time by using this (it's important to note that you can start it over and over again, the recursive calls do not make a new service.):

startService(new Intent(this, Timer.class));

Use System.currentTimeMillis to get the current system time, then add 60000 milliseconds to the time and store that as an end time. Then any time you have to change anything, just compare System.currentTimeMillis to the EndTime.

Endtime = System.currentTimeMillis + 60000;

then on every instance

TimeRemaining = Endtime - System.currentTimeMillis
spacebiker

The accepted answer makes the thing very complex. You can do it in a simpler way. The problem in your code is that Activity gets created on rotation (see Activity Lifecycle), so does the CountdownTimer instance.

I could write the whole example code but there is a nice answer from @Drew here: Android Innerclass TextView reference when activity resumes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!