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:

        

<span style="font-size:14px;">/**
 * 
 */
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;

	@Override
	protected 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() {

			@Override
			public void onClick(View v) {
				ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(
						1);
				Runnable command = new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (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);
			};
		});
	}
}
</span>

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。