android 定时广播,做定时器

时间:2021-10-17 23:24:15
        //定义AlarmManager 
private AlarmManager am = null;
//实例化AlarmManager
  am = (AlarmManager) getSystemService(ALARM_SERVICE);
// 注册广播
IntentFilter filter1 = new IntentFilter();
filter1.addAction("com.xx.alarm");
registerReceiver(alarmReceiver, filter1);

Intent intent = new Intent();
intent.setAction("com.xx.alarm");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);


am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),

1000*60, pi);// 马上开始,每分钟触发一次



 BroadcastReceiver alarmReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
// Toast.makeText(context, ++i, 0).show();
if(canUpload){
UploadFile();
}
}
//判断是否同一个时间内
};