Wednesday, May 23, 2012

Create alarm set on a specified time, using AlarmManager and BroadcastReceiver.


In this exercise, set alarm using AlarmManager to trigger our BroadcastReceiver on a specified time. We will use "TimePickerDialog" to set the target time.

Alarm will be triggered on a specified time


Modify main.xml to add a Button to start the TimePickerDialog to set the alarm time, add a TextView to display the set time.

<?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" />
    <Button
        android:id="@+id/startSetDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:text="Set Target Time"/>
    <TextView
        android:id="@+id/alarmprompt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

In the main activity, AndroidTimeActivity, the main code to start Alarm is in setAlarm(Calendar targetCal) method. Retrieve AlarmManager by through getSystemService(Context.ALARM_SERVICE). And set our alarm with alarm type(RTC_WAKEUP), trigger time, and pendingIntent. AlarmReceiver is the class of our BroadcastReceiver, it's onReceive() method will be called when alram trigger.

AndroidTimeActivity.java
package com.exercise.AndroidTime;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
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.TextView;
import android.widget.TimePicker;

public class AndroidTimeActivity extends Activity {
 
 TimePicker myTimePicker;
 Button buttonstartSetDialog;
 TextView textAlarmPrompt;
 
 TimePickerDialog timePickerDialog;
 
 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);
        
        textAlarmPrompt = (TextView)findViewById(R.id.alarmprompt);
        
        buttonstartSetDialog = (Button)findViewById(R.id.startSetDialog);
        buttonstartSetDialog.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    textAlarmPrompt.setText("");
    openTimePickerDialog(false);
    
   }});

    }

  
 private void openTimePickerDialog(boolean is24r){
  Calendar calendar = Calendar.getInstance();
  
  timePickerDialog = new TimePickerDialog(
    AndroidTimeActivity.this, 
    onTimeSetListener, 
    calendar.get(Calendar.HOUR_OF_DAY), 
    calendar.get(Calendar.MINUTE), 
    is24r);
  timePickerDialog.setTitle("Set Alarm Time");  
        
  timePickerDialog.show();

 }
    
    OnTimeSetListener onTimeSetListener
    = new OnTimeSetListener(){

  @Override
  public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

   Calendar calNow = Calendar.getInstance();
   Calendar calSet = (Calendar) calNow.clone();

   calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
   calSet.set(Calendar.MINUTE, minute);
   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);
  }};

 private void setAlarm(Calendar targetCal){

  textAlarmPrompt.setText(
    "\n\n***\n"
    + "Alarm is set@ " + targetCal.getTime() + "\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.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
  
 }
  
}

AlarmReceiver.java
package com.exercise.AndroidTime;

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) {
  Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();

 }

}

Modify AndroidManifest.xml to add receiver ".AlarmReceiver".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.exercise.AndroidTime"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AndroidTimeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".AlarmReceiver" android:process=":remote" />
    </application>

</manifest>


Download the files.

Next:
- Cancel alarm with a matching PendingIntent

Related:
- Set alarm on specified date/time with DatePicker/TimePicker

25 comments:

Unknown said...

thank you so much for this tutorial but i am wondering if you can show me how to add DatePiker besides the timePiker

Unknown said...
This comment has been removed by the author.
xxx said...

I wanna ask to you.
Is this just for one day, or repeatly everyday and everyweek?
If just one day, can you share how to set the alarm repeatly everyday and everyweek?

Erik said...

hello xxx,

please read schedule a repeating alarm.

Anonymous said...

Thank you, for the wonderful tutorial. It was exactly what i was looking for.

Unknown said...

thank you so much but i want to set Alarm in Timepicker and add it into a listview. How to do it?, I created a listview but it display one time on list

RA said...

can you explain How to stop repeating alarm at specific time ?

Erik said...

To stop a alarm, please read Cancel alarm with a matching PendingIntent

Rhane Beibeh said...

that just set alarm for one day
how to set alarm for time i want??

Unknown said...

how to set voice in alarm app at particular target time that alarm ring?

Erik said...

hello lipi shah,

read Generate Notification with sound when alarm received.

Unknown said...

Perfect! Work ok
Just what i was looking for!

Thanks!!

Edwin said...

Many thanks for sharing .... please help me as I do to open an activity in the same application when the alarm goes off?

Unknown said...

Your tutorial is awesome... but how to set sound after alarm received??@Andr.oid Eric

Erik said...

You can do anything in onReceive() once alarm reached.

Unknown said...

Very very Nice thank u...............

Rachmat said...

Thank you, this tutorial really help

Anonymous said...

Hi,
I wanna ask to you,how can I use notification in this project instead of Toast? Thank you

YO said...

hi, as is done in order to submit more than one alarm ??? Example 5 alarms with different names ???

Unknown said...

Thanks its working

2024, It’s Election Year said...

I going to build a app in which two button one for starting time and end time, if the user select the time for silent the mobile acorcoding to start time and unsilent mobile when the end time matched, how to do in android plz help I am a new.

Drashti said...

hello ,I am developing reminder application .After reminder rings i have updated time in Broadcast receiver class so now the time is update but my reminder doesnt ring for this new time.I dont knw what is the problemm.Please help mee

Unknown said...

It doesn't work

Unknown said...

thanks for this tutorial .I wonder how to set multiple alarms ?

Unknown said...

Hello all,
Am trying to create an Application where it silents a mobile based upon start_time and end time using timepicker.
Can anyone help with me in this..?