Simple Android AlarmManager Example to Schedule an Event

Simple Android AlarmManager Example to Schedule an Event

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

After getting so many request from users for updating the post on how to use Android alarm to schedule an event. Here is the complete example with source code and description. My idea is to give you a better idea about how AlarmManager works in Android platform. To make the example very simple, in this example we will have an activity which contains a button call ‘Setup Alarm’. Just click the button and wait for 10 seconds. Our Alarm will be raise. We can set any date/time to schedule the
alarm. In this example we have scheduled the alarm time by taking the current time + 10 seconds. So after click the button ‘Set Alarm’, we have to wait for next 10 seconds and we can see a toast message.

 

Here we will learn about Android AlarmManager example to schedule an event  in a very efficient way.

1. Register AlarmManager BroadcastReceiver.

2. Schedule date/time by using running instance of AlarmManager.

3. Cancel Scheduled Alarm at any time from your code.

Example  Description Details:

  • Create new android project in Eclipse (I am using Indigo) [File >> New >> Android Project] with Project Name: AlarmManagerExample. 
  • Click next and select target SDK 1.6 or higher. You can also just use default values in your eclipse while creating this project.
  • Click next and enter package name – ‘com.techblogon.alarmmanagerexample’
  • Click finish.

1. Layout:
We need to create one simple layout, which will contain one button called ‘Set Alarm’ and a simple textview to show some hints. The text view is optional in this case.

activity_main.xml:

Open your default xml file under /res/layout and replace it with the below XML.

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”.MainActivity” >

<TextView
android:id=”@+id/TextView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Android Alarm Example:\n\rSetup an alarm event after 10 seconds from the current time. So just press Setup Alarm button and wait for 10 seconds. You can see a toast message when your alarm time will be reach.” />

<Button
android:id=”@+id/setAlarm”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_below=”@+id/TextView1″
android:layout_centerHorizontal=”true”
android:layout_marginTop=”25dp”
android:onClick=”onClickSetAlarm”
android:text=”Set Alarm” />

</RelativeLayout>

 2. MainActivity.java

Now coming to our java code. Entire AlarmManager code is here. Have a into below code, then we will discuss line by line

package com.techblogon.alarmmanagerexample;

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

//used for register alarm manager
PendingIntent pendingIntent;
//used to store running alarmmanager instance
AlarmManager alarmManager;
//Callback function for Alarmmanager event
BroadcastReceiver mReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Register AlarmManager Broadcast receive.
RegisterAlarmBroadcast();
}
public void onClickSetAlarm(View v)
{
//Get the current time and set alarm after 10 seconds from current time
// so here we get
alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000 , pendingIntent );
}
private void RegisterAlarmBroadcast()
{
Log.i(“Alarm Example:RegisterAlarmBroadcast()”, “Going to register Intent.RegisterAlramBroadcast”);

//This is the call back function(BroadcastReceiver) which will be call when your
//alarm time will reached.
mReceiver = new BroadcastReceiver()
{
private static final String TAG = “Alarm Example Receiver”;
@Override
public void onReceive(Context context, Intent intent)
{
Log.i(TAG,”BroadcastReceiver::OnReceive() >>>>>>>>>>>>>>>>>>>>>>>>>>>>>”);
Toast.makeText(context, “Congrats!. Your Alarm time has been reached”, Toast.LENGTH_LONG).show();
}
};

// register the alarm broadcast here
registerReceiver(mReceiver, new IntentFilter(“com.techblogon.alarmexample”) );
pendingIntent = PendingIntent.getBroadcast( this, 0, new Intent(“com.techblogon.alarmexample”),0 );
alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}
private void UnregisterAlarmBroadcast()
{
alarmManager.cancel(pendingIntent);
getBaseContext().unregisterReceiver(mReceiver);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
}

Code Description:

  • In the above code we have used 3 class variable for complete the AlarmManager task

//used for register alarm manager
PendingIntent pendingIntent;
//used to store running alarmmanager instance
AlarmManager alarmManager;
//Callback function for Alarmmanager event
BroadcastReceiver mReceiver;

  •  To make this example simple, we have created 2 functions called RegisterAlarmBroadcast()and UnregisterAlarmBroadcast(). We will first register the alarm using function RegisterAlarmBroadcast(). In this example we have registered the alarmbroadcast in onCreate() function. Your onReceive() function will be called when your schedule time will be reached.
  • Then when use click on “Set Alarm” button, the function onClickSetAlarm() will be called from java code as above. In this function we will set/schedule the alarm. we have taken current time and add 10 seconds (10000 milliseconds) to schedule the alarm just 10 seconds after the current time.

public void onClickSetAlarm(View v)
{
//Get the current time and set alarm after 10 seconds from current time
// so here we get
alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000 , pendingIntent );
}

  • We can also cancel the scheduled alarm by calling the function UnregisterAlarmBroadcast() from any where from your code.
  • AlarmManager needs cleanup after exit from the application. For that we can use the android function unregisterReceiver() from onDestroy() override method.

3. Then build and run the application. Click on ‘Set Alarm” button and wait for 10 seconds. That’s it. Note: For real uses of AlarmManager, it is recomended to use Android background service and separate thread.

Leave a Reply

Your email address will not be published. Required fields are marked *