本文实例为大家分享了Android实现定时任务功能的具体代码,供大家参考,具体内容如下
1、采用Handle与线程的sleep(long)方法
(1)、定义一个Handler类,用于处理接受到的Message。
Handler handler = new Handler() {
public void handleMessage(Message msg) {
// 要做的事情
super.handleMessage(msg);
}
};
(2)、新建一个实现Runnable接口的线程类,如下:
public class MyThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);// 线程暂停10秒,单位毫秒
Message message = new Message();
message.what = 1;
handler.sendMessage(message);// 发送消息
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
(3)、在需要启动线程的地方加入下面语句:
new Thread(new MyThread()).start();
2、采用Handler的postDelayed(Runnable, long)方法
(1)、定义一个Handler类
Handler handler=new Handler();
Runnable runnable=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//要做的事情
handler.postDelayed(this, 2000);
}
};
(2)、启动
handler.postDelayed(runnable, 2000);
3、用Handler与timer及TimerTask结合的方法
(1)、定义定时器、定时器任务及Handler句柄
private final Timer timer = new Timer();
private TimerTask task;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
// 要做的事情
super.handleMessage(msg);
}
};
(2)、初始化计时器任务
task = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
(3)、启动和关闭定时器
timer.schedule(task, 2000, 3000);
timer.cancel();
4、采用AlarmManger实现长期精确的定时任务
(1)、服务类:
public class HorizonService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
Log.d("TAG", "打印时间: " + new Date().
toString());
}
}).start();
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
int five = 5000; // 这是5s
long triggerAtTime = SystemClock.elapsedRealtime() + five;
Intent i = new Intent(this, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
return super.onStartCommand(intent, flags, startId);
}
}
(2)、广播接受器
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, HorizonService.class);
context.startService(i);
}
}
(3)、启动定时任务:
Intent intent = new Intent(this,HorizonService.class);
startService(intent);