您的位置:首页 > 移动开发 > Android开发

android开发步步为营之59:android定时任务之ScheduledThreadPoolExecutor

2015-05-16 23:03 826 查看
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;

@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);
};
});
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: