从主线程调度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);
}

阅读更多
文章标签: 任务
个人分类: android_基础知识
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭