Android Activity Refreshing On Rotation

孤街醉人 提交于 2019-12-05 20:22:01
Menelaos Kotsollaris

However, I discovered that the async class is still running but the UI doesn't change because (I think) the activity now has a different context to the one the async class has reference to.

Nice guess. You have to handle the Activity's lifecycle, if you want to keep the computed data since whenever you rotate the device, the activity is getting recreated thus onCreate() is getting called without saving the previous computed data. You have to override onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState() in order to save your computations. Take a look at the Activity's LifeCycle documentation and Reto Meier's answer, I think it will solve your problem.

In your CountDownTimer implement onTick:

@Override
public void onTick(long millisUntilFinished) {
    // something like this:
    this.millisUntilFinished = millisUntilFinished;
}

In your Activity implement onSaveInstanceState:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // something like this:
    savedInstanceState.putLong("millisUntilFinished", millisUntilFinished);
}

also in onCreate and onStart re-setup your CountDownTimer:

@Override
public void onCreate(Bundle savedInstanceState) {
    // ...

    if (savedInstanceState != null) {
        millisUntilFinished = savedInstanceState.getLong("millisUntilFinished");
    }

}

@Override
public void onStart() {
    super.onStart();
    timer = new MyCountDownTimer(millisUntilFinished, 100); 
    timer.start();
}

Don't copy this code verbatim, there are a few details missing/assumptions made that will be different in your code, but it could look something like this.

The solution from Try_me34 is good, but here are some other ways to save and restore data (can't post them as a comment):

Try overriding the onPause method and save the process to a secondary class (a Timer, maybe) and then restore it overriding onResume.

Another option is to save it as a preference:

SharedPreferences.Editor editor = getSharedPreferences("nameOfFile", MODE_PRIVATE).edit();
editor.putInt("name", value);
editor.putString("nameForString", value);

And then load it:

SharedPreferences prefs = getSharedPreferences("nameOfFile", MODE_PRIVATE);
int i = prefs.getInt("tag", 0);
String s = prefs.getString("tag", "defaultValue");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!