Friday, May 25, 2012

schedule a repeating alarm

To schedule a repeating alarm, call setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation) method of AlarmManager instead of set(int type, long triggerAtTime, PendingIntent operation).

Schedule a repeating alarm

Modify from last post "Cancel alarm with a matching PendingIntent". (Also change using TimePicker widget instead of TimePickerDialog)

package com.exercise.AndroidTime;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;

public class AndroidTimeActivity extends Activity {
 
 TimePicker myTimePicker;
 Button buttonstartSetDialog;
 Button buttonCancelAlarm;
 TextView textAlarmPrompt;
 
 TimePicker timePicker;
 CheckBox optRepeat;
 
 final static int RQS_1 = 1;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        timePicker = (TimePicker)findViewById(R.id.picker);
        optRepeat = (CheckBox)findViewById(R.id.optrepeat);
        textAlarmPrompt = (TextView)findViewById(R.id.alarmprompt);
        
        buttonstartSetDialog = (Button)findViewById(R.id.startSetDialog);
        buttonstartSetDialog.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    Calendar calNow = Calendar.getInstance();
    Calendar calSet = (Calendar) calNow.clone();

    calSet.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
    calSet.set(Calendar.MINUTE, timePicker.getCurrentMinute());
    calSet.set(Calendar.SECOND, 0);
    calSet.set(Calendar.MILLISECOND, 0);
    
    if(calSet.compareTo(calNow) <= 0){
     //Today Set time passed, count to tomorrow
     calSet.add(Calendar.DATE, 1);
    }
    
    setAlarm(calSet, optRepeat.isChecked());
    
   }});

        buttonCancelAlarm = (Button)findViewById(R.id.cancel);
        buttonCancelAlarm.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    cancelAlarm();
   }});
        
    }

 private void setAlarm(Calendar targetCal, boolean repeat){
  
  Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
  AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
  alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);

  if(repeat){
   alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
     targetCal.getTimeInMillis(), 
     TimeUnit.MINUTES.toMillis(5),
     pendingIntent);
   
   textAlarmPrompt.setText(
     "\n\n***\n"
     + "Alarm is set@ " + targetCal.getTime() + "\n"
     + "Repeat every 5 minutes\n"
     + "***\n");
  }else{
   alarmManager.set(AlarmManager.RTC_WAKEUP, 
     targetCal.getTimeInMillis(),  
     pendingIntent);
   
   textAlarmPrompt.setText(
     "\n\n***\n"
     + "Alarm is set@ " + targetCal.getTime() + "\n"
     + "One shot\n"
     + "***\n");
  }

 }
 
 private void cancelAlarm(){

  textAlarmPrompt.setText(
    "\n\n***\n"
    + "Alarm Cancelled! \n"
    + "***\n");
  
  Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
  AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
  alarmManager.cancel(pendingIntent);

 }
  
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <TimePicker
        android:id="@+id/picker"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <CheckBox
        android:id="@+id/optrepeat"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Repeat every 5 minutes" />
    <Button
        android:id="@+id/startSetDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:text="Set Target Time"/>
    <Button
        android:id="@+id/cancel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:text="Cancel Alarm"/>
    <TextView
        android:id="@+id/alarmprompt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>


Both AlarmReceiver.java and AndroidManifest.xml keep no change, refer to the exercise "Create alarm set on a specified time, using AlarmManager and BroadcastReceiver."


Download the files.


Next:
- Generate Notification using Notification.Builder for Android 3.0


5 comments:

  1. Hello, It is a very nice tutorial provided here. Also there are lots of other helpful articles. I am having question related to this article that you are repeating the task after every 5min but can you provide me some way that i can repeat it for specific day. For e.g repeat the alarm on every Monday. Please kindly help me if you have any idea regarding this. Thanks a lot for writing such a nice articles.

    ReplyDelete
  2. Why it does not make any difference when the setting time comes?

    ReplyDelete
  3. Can you see the Toast "Alarm received!"?

    ReplyDelete
  4. Hi, first of all, congrats for an amazing series of tutorials... you've been a help to a lot of young android developers..

    I just have 1 question, that I would appreciate if you could answer:
    - when you restart the android device, the previously schedule alarms disappear... is there a way to ensure that the "cache" doesn't get erase?

    ReplyDelete
  5. thank you so much for your tutorial. can you appear tutorial alarm with tone? thanks

    ReplyDelete