android中的定时任务。由AlarmManager对象进行管理
1.定时唤醒广播接受者
直接贴代码,在代码中说明
AlarmController.java
public class AlarmController extends Activity{
private Toast mToast;
private static final String TAG = "app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm_controller);
Button button = (Button)findViewById(R.id.one_shot);
button.setOnClickListener(oneShotListener);
button = (Button)findViewById(R.id.start_repeating);
button.setOnClickListener(startRepeatingListener);
button = (Button)findViewById(R.id.stop_repeating);
button.setOnClickListener(stopRepeatingListener);
}
private OnClickListener oneShotListener = new OnClickListener() {
@Override
public void onClick(View v) { //只进行一次定时,不重复执行
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 30); //设置30秒后执行
/*
* 根据PendingIntent.getBroadcast
* 指明定时唤醒广播接收者
* */
PendingIntent pending = PendingIntent.getBroadcast(AlarmController.this,
0, new Intent(AlarmController.this,OneShotAlarm.class), 0);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending); //表示在指定时间后执行
if(mToast!=null){
mToast.cancel();
}
mToast.makeText(AlarmController.this, "one_shot_scheduled", Toast.LENGTH_LONG).show();
}
};
private OnClickListener startRepeatingListener = new OnClickListener() {
@Override
public void onClick(View v) { //重复执行
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pend = PendingIntent.getBroadcast(AlarmController.this,
0, new Intent(AlarmController.this,RepeatingAlarm.class), 0);
long triggerAtTime = SystemClock.elapsedRealtime();
triggerAtTime +=15*1000; //表示第一次执行15秒后
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
triggerAtTime, 15*1000, pend); //表示过15秒重复唤醒广播接受者
if(mToast!=null){
mToast.cancel();
}
mToast.makeText(AlarmController.this, "repeating_scheduled", Toast.LENGTH_LONG).show();
}
};
private OnClickListener stopRepeatingListener = new OnClickListener() {
@Override
public void onClick(View v) { //取消alarm
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pend = PendingIntent.getBroadcast(AlarmController.this,
0, new Intent(AlarmController.this,RepeatingAlarm.class), 0);
am.cancel(pend);
if(mToast!=null){
mToast.cancel();
}
mToast.makeText(AlarmController.this, "stop_repeating_scheduled", Toast.LENGTH_LONG).show();
}
};
}
然后可以定期执行OneShotAlarm和RepeatingAlarm中的onRecevier中的内容
2.1.定时创建service
关键代码:
//注意此方法PendingIntent.getService()
PendingIntent pend = PendingIntent.getService(this, 0,
new Intent(this,AlarmService_Service.class), 0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
long firstTime = SystemClock.elapsedRealtime();
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 15*1000, pend);
完整例子: