The AlarmManager class allows you to schedule recurring alarms that will work at specified points in the future. AlarmManager gets the PendingIntent to start when an alarm is scheduled. When an alarm triggered, a registered Intent is broadcast by the Android system, launching the target application, if it is not already running.
Create a class that inherits from BroadcastReceiver. In the onReceive method, which is called when BroadcastReceiver receives an Intent broadcast, we will create code that performs our task.
AlarmReceiver.java
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent arg1) {
Then we need to register the BroadcastReceiver in the manifest file. Declare AlarmReceiver in the manifest file.
<application> . . <receiver android:name=".AlarmReceiver"></receiver> . . </application>
The following instance variables are included in your calling activity.
private PendingIntent pendingIntent; private AlarmManager manager;
In onCreate (), we create an Intent that references our broadcast receive class and uses it in our PendingIntent.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
Then we turn on a method that will set up repeated alarms. After setting, the alarm will be triggered after every Xth time, here we take an example of 10 seconds, you can simply calculate this to call it every day.
public void startAlarm(View view) { manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); int interval = 10000; manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent); Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show(); }
Next, also configure the cancelAlarm () method to stop alarms if necessary.
public void cancelAlarm(View view) { if (manager != null) { manager.cancel(pendingIntent); Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show(); } }