1

Say, if I want the CountDownTimer to update some UI elements when it has finished, but there is a configuration change in the middle of the countdown, forcing the activity to be recreated.

public class MyActivity extends Activity {

    private TextView textView;

    ....

    public void onButtonClicked(View view)
    {
        // start CountDownTimer
        new CountDownTimer(10000, 10000) {
            public void onTick(long millisUntilFinished) {
                // do nothing
            }
            public void onFinish() {
                textView.setText("Hello World!");
            }
        }.start();
    }

}

I find that when the CountDownTimer finishes, it set the textView in the activity just got destroyed, but not the recreated one

4

3 に答える 3

1

http://developer.android.com/guide/topics/resources/runtime-changes.html

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString("timer",1223);

// etc.
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
 time = savedInstanceState.getString("time");
}

When you have large sets of data like data from database or arraylist.

@Override 
public Object onRetainNonConfigurationInstance() {
final MyDataObject data = collectMyLoadedData(); 
return data;
}

In onCreate

 final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance();
if (data == null) {
    data = loadMyData();
}
于 2013-03-24T08:06:37.723 に答える
0

You can store if your count is finish or not in a file

http://developer.android.com/guide/topics/data/data-storage.html

and refer to this file after

于 2013-03-24T08:04:50.493 に答える
0

I have implemented a pausable CountDownTimer and pause/resume it when onPause()/onResume() is called, and reference it in a fragment with setRetainInstance(true). It can now keep its progress after screen rotation or any configuration changes.

于 2013-03-26T20:19:17.430 に答える