从主线程调度runnable任务

实现一个计时器的功能


long mStartTime = 0L;     TextView mTileLabel;

Handler mHandler = new Handler();

public void onCreate(Bundle savedInstanceState) {

     if(mStartTime == 0L){
    mStartTime = SystemClock.uptimeMillis();
   
 mHandler.removeCallbacks(mUpdateTimeTask);
    mHandler.postDelayed(mUpdateTimeTask, 1000);
     }

}

    private Runnable mUpdateTimeTask = new Runnable(){

@Override
public void run() {
final long start = mStartTime;
long millis = SystemClock.uptimeMillis() - start;
int seconds = (int)( millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
mTileLabel.setText("" + minutes + ":" +String.format("%02d", seconds));
mHandler.postDelayed(this, 200);
}
 
 };

protected void onPause() {
mHandler.removeCallbacks(mUpdateTimeTask);
super.onPause();
}



protected void onResume() {
super.onResume();
mHandler.postDelayed(mUpdateTimeTask, 100);
}

你可能感兴趣的:(从主线程调度runnable任务)