我正在尝试编写一个包含倒数计时器的活动。我通过一个新线程创建它,当应用程序被发送到后台时,这个倒数计时器继续在他的线程中运行;问题是当我再次开始活动时;这会创建另一个执行相同操作的线程。
那么,有什么方法可以“恢复”在应用程序发送到后台之前创建的先前线程,而无需创建新副本?
这是代码:
public class MainActivity extends FragmentActivity{
private static final String TAG = Values.Tags.MAIN_ACTIVITY;
private TextView timeTextView;
final Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
// GENERAL ACTIVITY TASKS (all activities should do these).
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// MAIN_ACTIVITY TASKS.
timeTextView = (TextView) findViewById(R.id.activityMain_timer);
createThread();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void buttonPressed(View view){
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, 0, 0, true);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Log.d(TAG, "set time");
getPickedTime(hourOfDay, minute);
}
}
public static void getPickedTime(int hourOfDay, int minute) {
Log.d(TAG, "Hora: "+hourOfDay+", minute: "+minute);
}
private void createThread() {
Thread thread = new Thread(){
public void run(){
try {
Thread.sleep(10000);
} catch (InterruptedException e){
Log.d(TAG, e.getMessage());
}
Log.d(TAG, this.getName()+ " is about to complete...");
mHandler.post(doAction);
}
};
thread.setName("thread00");
thread.start();
}
final Runnable doAction = new Runnable(){
public void run(){
Log.d(TAG, "Completed.");
}
};
}
谢谢。