android開發步步為營之59:android定時任務之ScheduledThreadPoolExecutor,
android定時任務有多種,1、Timer+TimerTask 2、Handler.postDelay 3、AlarmManager 4、ScheduledThreadPoolExecutor,前面3種比較常見,相信大家也經常使用,本文介紹採用多線程的ScheduledThreadPoolExecutor,它相比jdk 1.5的Timer的優點有幾點:1、採用多線程,Timer是單線程,一旦Timer裡面任何一個TimerTask異常的話,整個Timer線程就會停止 2、Timer依賴電腦自身的時間,比如預約10分鐘後執行任務,電腦時間往前調個5分鐘,那麼這個任務5分鐘後就開始執行了,而ScheduledThreadPoolExecutor採用相對時間,不管電腦時間調前還是調後了,不受影響。jdk1.5之後都推薦使用ScheduledThreadPoolExecutor,開始我們本文的demo,我們這個demo是做一個秒錶,每一秒執行一次任務,然後更新TextView數字。請看demo:
/** * */package com.figo.study;import java.util.concurrent.ScheduledThreadPoolExecutor;import java.util.concurrent.TimeUnit;import com.figo.study.utils.StringUtils;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;/** * @author figo * */public class ScheduledThreadPoolExecutorActivity extends Activity {TextView tv_time;Handler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) {// 更新時間handler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case 1:tv_time.setText(msg.getData().getString("num"));break;}super.handleMessage(msg);}};super.onCreate(savedInstanceState);setContentView(R.layout.activity_scheduledthreadpool);Button btnShedule = (Button) findViewById(R.id.btnschedule);tv_time = (TextView) findViewById(R.id.tv_time);btnShedule.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);Runnable command = new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubif (StringUtils.isNotEmpty(tv_time.getText().toString())) {int time = Integer.parseInt(tv_time.getText().toString());time = time + 1;Message message = new Message();message.what = 1;Bundle data = new Bundle();data.putString("num", String.valueOf(time));message.setData(data);handler.sendMessage(message);// 在非UI線程更新無效,必須在外面UI主線程更新// tv_time.setText(String.valueOf(time));} else {// tv_time.setText("0");}}};//java.util.concurrent.ScheduledThreadPoolExecutor.scheduleAtFixedRate//(Runnable command, long initialDelay, long period, TimeUnit unit)scheduledThreadPoolExecutor.scheduleAtFixedRate(command, 1, 1,TimeUnit.SECONDS);};});}}