articles

AlarmManager with BroadcastReceiver in Android

AlarmManager with BroadcastReceiver in Android

Manoj Pandey20709 04-Mar-2015

AlarmManager is a class in Android which is used as an access device alarm service.

This allows your application to execute a certain piece of code on a given scheduled time. This can run outside the lifetime of your application.

Once the alarm is scheduled, it will invoke even when your application is not running or even your device is in sleep.

The alarm can wake your device, but this consumes more battery. This means is that you have to be careful while scheduling an alarm task that executes more frequently.

Android broadcast receiver is also a component where you can register for system or application events. You will be notified about the events after registering.

The broadcast originates from the system as well as applications. An instance of broadcast originating from the system is ‘low battery notification’.

There are two ways to register an Android broadcast receiver.

One is a static way in which the broadcast receiver is registered in an android application via the AndroidManifest.xml file.

Another way of registering the broadcast receiver is dynamic, which is done using Context.registerReceiver() method.

Dynamically registered broadcast receivers can be unregistered using Context.unregisterReceiver() method.

Here is a sample of Alarm managers who perform the action of alarm and show notification of alarm.

  • Create an Android project
  • My activity_main.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"

    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=".MyActivity" >

 

    <TimePicker

        android:id="@+id/alarmTimePicker"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true" />

 

    <ToggleButton

        android:id="@+id/alarmToggle"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/alarmTimePicker"

        android:layout_centerHorizontal="true"

        android:text="Alarm On/Off" />

 

    <TextView

        android:id="@+id/alarmText"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentBottom="true"

        android:layout_below="@+id/alarmToggle"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="20dp"

        android:text=""

        android:textAppearance="?android:attr/textAppearanceLarge"/>

 

</RelativeLayout>

3.       AlarmActivity.class 

package com.example.androidalarm; 

import android.app.Activity;

import android.app.AlarmManager;

import android.app.PendingIntent;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.TextView;

import android.widget.TimePicker;

import android.widget.Toast;

import android.widget.ToggleButton;

 

import java.util.Calendar;

 

public class AlarmActivity extends Activity {

 

     AlarmManager alarmManager;

     private PendingIntent pendingIntent;

     private TimePicker alarmTimePicker;

     private static AlarmActivity inst;

     private TextView alarmTextView;

 

     public static AlarmActivity instance() {

           return inst;

     }

 

     @Override

     public void onStart() {

           super.onStart();

           inst = this;

     }

 

   @Override

  protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_main);

       // get view from layout

     alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);

           alarmTextView = (TextView) findViewById(R.id.alarmText);

           final ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);

 

           // use alarm service

          alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

           // toggle button click listner

           alarmToggle.setOnClickListener(new OnClickListener() {

 

                @Override

                public void onClick(View v) {

                     // TODO Auto-generated method stub

                     try {

                           if (alarmToggle.isChecked()) {

                   Toast.makeText(getApplicationContext(), "Alarm On",

                                           Toast.LENGTH_SHORT).show();

                           Calendar calendar = Calendar.getInstance();

                      // set selected time from timepicker to calendar

                              calendar.set(Calendar.HOUR_OF_DAY,

                                    alarmTimePicker.getCurrentHour());

                               calendar.set(Calendar.MINUTE,

                                   alarmTimePicker.getCurrentMinute());

 

                     Intent myIntent = new Intent(AlarmActivity.this,

                                           AlarmReceiver.class);

 

                 // A PendingIntent specifies an action to take in the

                                // future

                     pendingIntent = PendingIntent.getBroadcast(

                             AlarmActivity.this, 0, myIntent, 0);

 

                                // set alarm time

                            alarmManager.set(AlarmManager.RTC,

                           calendar.getTimeInMillis(), pendingIntent);

                           } else {

                                // Cancel alarm

                                alarmManager.cancel(pendingIntent);

                  Toast.makeText(getApplicationContext(), "Alarm Off",

                                           Toast.LENGTH_SHORT).show();

                                setAlarmText("");

                           }

                     } catch (Exception ex) {

 

                     }

 

                }

           });

     }

 

     public void setAlarmText(String alarmText) {

           alarmTextView.setText(alarmText);

     }

}

 

PendingIntent-: A PendingIntent specifies an action to take in the future. It lets you pass a future Intent to another application and allow that application to execute that Intent as if it had the same permissions as your application, whether or not your application is still around when the Intent is eventually invoked. It is a token that you give to a foreign application which allows the foreign application to use your application’s permissions to execute a predefined piece of code

4.      Create an AlarmReceiver class and this class extended by WakefulBroadcastReceiver class and you can also use BroadcastReceiver instead of WakefulBroadcastReceiver. This class takes care of creating and managing a partial wake lock for you; you must request the WAKE_LOCK permission to use it.


Add following code in AlarmReceiver class

 

package com.example.androidalarm; 

import android.app.Activity;

import android.content.BroadcastReceiver;

import android.content.ComponentName;

import android.content.Context;

import android.content.Intent;

import android.media.MediaPlayer;

import android.media.Ringtone;

import android.media.RingtoneManager;

import android.net.Uri;

import android.support.v4.content.WakefulBroadcastReceiver;

import android.widget.Toast;

 

public class AlarmReceiver extends WakefulBroadcastReceiver // BroadcastReceiver

{

 

                @Override

                public void onReceive(final Context context, Intent intent) {

                                // this will update the UI with message

                                try {

                                                AlarmActivity inst = AlarmActivity.instance();

                                                inst.setAlarmText("Alarm! Wake up! Wake up!");

 

                                                // this will sound the alarm tone

                                                // this will sound the alarm once, if you wish to

                                                // raise alarm in loop continuously then use MediaPlayer and

                               

                                                Uri alarmUri = RingtoneManager

                                                                           .getDefaultUri(RingtoneManager.TYPE_ALARM);

                                                if (alarmUri == null) {

                                                                alarmUri = RingtoneManager

                                                               .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

                                                }

                                    Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);

                                                ringtone.play();

 

                                                // this will send a notification message

                       ComponentName comp = new ComponentName(context.getPackageName(),

                                                                                AlarmService.class.getName());

                                                intent.setComponent(comp);

 

                                 // If extended by BroadcastReceiver class then comment this code

                                                startWakefulService(context, (intent.setComponent(comp)));

                               

 

                                                setResultCode(Activity.RESULT_OK);

                                } catch (Exception ex) {

 

                                }

                }

}

5.       Add new class AlarmService and extend with IntentService. Add the following code in this class

 

package com.example.androidalarm;

 

import android.app.IntentService;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.Context;

import android.content.Intent;

import android.support.v4.app.NotificationCompat;

 

public class AlarmService extends IntentService {

     private NotificationManager alarmNotificationManager;

 

     public AlarmService() {

           super("AlarmService");

     }

 

     @Override

     public void onHandleIntent(Intent intent) {

           sendNotification("Wake Up! Wake Up!");

     }

 

     private void sendNotification(String msg) {

           // NotificationManager class to notify the user of events // that happen. This is how you tell the user that something // has happened in the background.

           alarmNotificationManager = (NotificationManager) this

                     .getSystemService(Context.NOTIFICATION_SERVICE);

 

       PendingIntent contentIntent = PendingIntent.getActivity(this, 0,

                     new Intent(this, AlarmActivity.class), 0);

 

           // set icon, title and message for notification

       NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(

          this).setContentTitle("Alarm")

           .setSmallIcon(R.drawable.ic_launcher)

          .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))

                     .setContentText(msg);

 

           alamNotificationBuilder.setContentIntent(contentIntent);

           alarmNotificationManager.notify(1, alamNotificationBuilder. build());

 

     }

}

6.       Add permission as well as define service  in Mainfest.xml fine

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.androidalarm"

    android:versionCode="1"

    android:versionName="1.0" >

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

    <uses-sdk

        android:minSdkVersion="14"

        android:targetSdkVersion="18" />

 

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="com.example.androidalarm.AlarmActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

          <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

 

        <service

            android:name="com.example.androidalarm.AlarmService"

            android:enabled="true" />

 

    <receiver android:name="com.example.androidalarm.AlarmReceiver" />

    </application>

 

</manifest>

 

Now run application

AlarmManager with BroadcastReceiver in Android

See the notification

AlarmManager with BroadcastReceiver in Android

 

 


Updated 07-Dec-2019

Leave Comment

Comments

Liked By