Alarm Example in Android


           Alarm is one of the best examples for BroadcastReceiver. This will be very useful to schedule an event after some amount of time even though the user has not opened the application. All we need to do is registering a broadcast. Android provides AlarmManager class which provides access to system alarm services. We The system will broadcast the Intent that had been registered using AlarmManager instance. This will happen when the alarm goes off. To know more about BroadcastReceiver concept visit this post.
We can schedule SMS to be sent or we can schedule a notification to the user using AlarmManager.
As stated in the AlarmManager javadoc, it holds a CPU wake lock as long as the alarm receiver's onReceive() is executing. This means the device will no go to sleep state until the user finishes the broadcast. The AlarmManager will release the lock after the execution of onReceive() method.

set() method of the AlarmManager is used to register an Intent to be sent.
Syntax:
set (int type, long triggerAtMillis, PendingIntent operation)
here type is - One of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC or RTC_WAKEUP.
triggerAtMillis is - time in milliseconds that the alarm should go off. 
operation is the Intent instance that will be sent when the alarm go off.

For example:

Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
  this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
    + (i * 1000), pendingIntent);


In this sample application we are going to vibrate the device using alarm manager after some time. So we have used VIBRATE permission in the manifest file.
<uses-permission android:name="android.permission.VIBRATE" />

If you get access denied exception while creating AlarmManager, then use SET_ALARM permission in your manifest file.
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

Do not forget to register the broadcast receiver in the manifest file.

<receiver android:name="MyBroadcastReceiver" >
</receiver>
MyBroadcastReceiver is the name of the java class extending BroadcastReceiver. onReceive() method needs to be implemented to do certain task. In this example we are just showing a notification to the user and starting vibrator service.

Project structure:




AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alarmexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.alarmexample.MainActivity"
            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="MyBroadcastReceiver" >
        </receiver>
    </application>

</manifest>

Layout xml file:

<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"
    tools:context=".MainActivity" >
 <EditText
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="28dp"
        android:ems="10"
        android:hint="Number of seconds"
        android:inputType="numberDecimal" />
    <Button

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="95dp"
        android:onClick="startAlert"
        android:text="Set" />

   

</RelativeLayout>


Activity java class:

package com.example.alarmexample;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/**
 * @author Prabu
 *
 */
public class MainActivity extends Activity {

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

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

 public void startAlert(View view) {
    EditText text = (EditText) findViewById(R.id.time);
    int i = Integer.parseInt(text.getText().toString());
    Intent intent = new Intent(this, MyBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
   this.getApplicationContext(), 234324243, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
   + (i * 1000), pendingIntent);
    Toast.makeText(this, "Alarm set in " + i + " seconds",
   Toast.LENGTH_LONG).show();
 }

}


MyBroadcastReceiver java class:

package com.example.alarmexample;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.widget.Toast;


/**
 * @author Prabu
 *
 */
public class MyBroadcastReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Time is up!!!!.",
   Toast.LENGTH_LONG).show();
    // Vibrate the mobile phone
    Vibrator vibrator = (Vibrator) context
  .getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(2000);
 }
}


Output screenshots:




Source code of this application:
AlarmExample.zip

 



Reactions:

3 comments :

  1. What is better to use broadcast receiver or service for notification using alarms

    ReplyDelete
  2. Love you!!!! Found many tutorials over the internet but you are simply awesome.

    ReplyDelete