运行 经常使用 AlarmManager 的任务

Running Frequently task using AlarmManager

我想 运行 在不告诉用户的情况下在后台执行一些任务,以将一些数据发送到服务器。

要求是,每隔十五分钟我必须发送一些数据。所以需要每 15 分钟触发一次警报。

我正在使用 AlarmManager 但没有实现。

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,5);
cal.set(Calendar.MINUTE,10);//
cal.set(Calendar.SECOND, 0);
Intent intent = new Intent(this, TaskReceiver.class);
pintent = PendingIntent.getService(this, 0, intent, 0);
alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
long repeatingTime = 2 * 60 * 1000;

alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),repeatingTime, pintent);

使用这个完成:

public static void registerAlarm(Context context) {
  Intent i = new Intent(context, TaskReceiver.class);

  PendingIntent sender = PendingIntent.getBroadcast(context, 147, i, 0);

  // We want the alarm to go off 3 seconds from now.
  long firstTime = SystemClock.elapsedRealtime();
  firstTime += 3 * 1000;//start 3 seconds after first register.

  // Schedule the alarm!
  AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
  am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
            600000, sender);//10min interval
}