android在项目中做定时发送器,每隔两小时发送一次

在onCreate中
@Override
public void onCreate() {
super.onCreate();
startTimer();
并且注册广播
IntentFilter timerFilter = new IntentFilter();
timerFilter.addAction(Constant.ACTION_TIMER_REQUEST_UP);
registerReceiver(myTimerReceiver, timerFilter);
}
public static long Constant.periodTime = 120601000;
protected synchronized void startTimer() {
//定义一个PendingIntent对象,PendingIntent.getBroadcast包含了sendBroadcast的动作。
Intent intent = new Intent(Constant.ACTION_TIMER_REQUEST_UP);
intent.setAction(Constant.ACTION_TIMER_REQUEST_UP);
//也就是发送了action 为"ACTION_TIMER_REQUEST_UP"的intent
PendingIntent pi = PendingIntent.getBroadcast(this,0,intent,0);
//AlarmManager对象,注意这里并不是new一个对象,Alarmmanager为系统级服务
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
//设置闹钟从当前时间开始,每隔执行一次PendingIntent对象pi,注意第一个参数与第二个参数的关系
// 通过PendingIntent pi对象发送广播
am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+Constant.periodTime,Constant.periodTime,pi);
}

猜你喜欢

转载自blog.csdn.net/Hh19900902/article/details/90747356