Code example for AlarmManager: Creating a periodic task

Methods: cancelsetsetRepeating

1
 
		if (command.contains("Start Alarm")) {
			alarmManager.set(AlarmManager.RTC_WAKEUP, time, pi);
		} else if (command.contains("Stop Alarm")) {
			pi.cancel(); 					// Cancel the pendingIntent.
			alarmManager.cancel(pi); 		// Cancel the alarm.
			 
			// If more times with a timeReminder exist, start a new alarm. 
			if (time != 0) alarmManager.set(AlarmManager.RTC_WAKEUP, time, pi);
		} else 
			Log.e("AlarmManagerService", "Command contained unknown value");
	} 
 
	/** 
	 * Method for starting or stopping the position alarm. 
	 * @param command decides whether to start or stop the alarm. 
	 */ 
	private void positionAlarm(String command) {
		// Let the receiver know its a position-alarm. 
		alarmReceiverIntent.putExtra("alarmType", "position");
 
		PendingIntent pi = PendingIntent.getBroadcast(context,
				LOCATION_REQUEST_CODE, alarmReceiverIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);
 
		if (command.contains("Start Alarm")) {
			// Start the alarm now, and start it again every 5 minutes: 
			alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
					SystemClock.elapsedRealtime(), MINUTE_IN_MILLIS * 5, pi);
		} else if (command.contains("Stop Alarm")) {
			pi.cancel(); 						// Cancel the pendingIntent.
			alarmManager.cancel(pi); 			// Cancel the alarm.
		} else 
			Log.e("AlarmManagerService", "Command contained unknown value");
	} 
}