Android AlarmManager - Start Alarm

January 23, 2018 Oclemy Android Alam 5 minutes, 13 seconds

One of those mobile-like software applications is the Alarm. Or any app that can schedule something to happen in the future. This is even more important in mobile devices than in desktop applications.

Because we never leave or power off our mobile devices. They are our personal assistants. So we use them in more personal ways than we would ever do with desktop applications.

So Android provides us a rich class called AlarmManager. A class that allows us access system services. The class is obviously public and derives from java.lang.Object.

Here's its definition:

    public class AlarmManager extends Object{}

What do we build?

Well let's see a simple android alarm manager example. We see how to start and cancel an alarm in android. We have a basic edittext. The user enters the time in miliseconds for the alarm to ring. The alarm rings by displaying a simple toast message.

Android AlarmManager

Project Structure

Here's the project structure:

Project Structure

Step 1 - Create Android Project

  • In your android studio go to File -- New -- New Project.
  • Type Project Name.
  • Choose minimum sdk.
  • From templates choose empty activity or bla.

Empty Activity Template

Step 2. - Let's modify our build.gradle.

This is our second step. Android projets created in android studio have two buil.gradle files. We are interested in the app level build.gradle.

Add the followng code under the dependencies section:

        compile 'com.android.support:appcompat-v7:24.2.1'
        compile 'com.android.support:design:24.2.1'

We've added two dependencies from support library: AppCompat and design.

Step 3. Let's prepare our resources.

The only resource we need to prepare in this case is the layouts. I chose the basic activity as my template. So I have two layouts:

  • _activitymain.xm : template layout
  • _contentmain.xml : this what we modify.

All I need is add one edittext and one button. The edittext where the user will enter the time in seconds and the start button to start the alarm.

     <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        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"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.tutorials.hp.alarmmanagerstarter.MainActivity"
        tools:showIn="@layout/activity_main">

        <EditText
            android:id="@+id/timeTxt"
            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:id="@+id/startBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/timeTxt"
            android:layout_below="@+id/timeTxt"
            android:layout_marginRight="60dp"
            android:layout_marginTop="120dp"
            android:text="Start" />
    </RelativeLayout>

Step 4. Let's create our BroadcastReceiver class.

A BroadcastReceiver is one of the android components. Others include Activity, Service and ContentProvider.
A BroadcastReceiver listens to System events.

It's actually an abstract class that's obviously public. It derives form java.lang.Object :

    public abstract class BroadcastReceiver extends Object{}

Intents sent by the sendBroadcast() will be received by this base class.

It's an abstract class so we will override the onReceive() method.

First create a java class :

    public class MyReceiver{}

Add the folowing imports:

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

Make it derive from android.content.BroadcastReceiver:

    public class MyReceiver extends BroadcastReceiver {}

This will force us to ovveride the onReceive() method:

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Alarm Ringing...", Toast.LENGTH_SHORT).show();
        }

Step 5. Let's come to our MainActivity class.

Activities are android components that represent a user interface. We create activities by deriving from an activity. To support more devices we use AppCompatActivity.

So let's create an activity:

    public class MainActivity extends AppCompatActivity {}

Add the following imports on top of the activity:

    import android.app.AlarmManager;
    import android.app.PendingIntent;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

Our activity will have three methods and two fields:

First we define our two fields: basically a button an edittext. Add them inside the MainActivity class:

        Button startBtn;
        EditText timeTxt;

Then we create a method go(). This method will be responsible for initializing our alarmmanager and starting the alarm:

        private void go()
        {
            //GET TIME IN SECONDS AND INITIALIZE INTENT
            int time=Integer.parseInt(timeTxt.getText().toString());
            Intent i=new Intent(this,MyReceiver.class);

            //PASS CONTEXT,YOUR PRIVATE REQUEST CODE,INTENT OBJECT AND FLAG
            PendingIntent pi=PendingIntent.getBroadcast(this,0,i,0);

            //INITIALIZE ALARM MANAGER
            AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);

            //SET THE ALARM
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+(time*1000),pi);
            Toast.makeText(MainActivity.this, "Alarm set in "+time+" seconds", Toast.LENGTH_SHORT).show();
        }

Then we come create another method to initialize our button and edittext and handle the onclick listener of the button:

        private void initializeViews()
        {
            timeTxt= (EditText) findViewById(R.id.timeTxt);
            startBtn= (Button) findViewById(R.id.startBtn);

            startBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                   go();
                }
            });
        }

Step 6. Let's check on the Androidmanifest

Go over the androidmanifest.xml. We want to ensure our BroadcastReceiver class is registered inside our manifest.

You can see that our broadcastreceiver class is registered:

            <receiver android:name="MyReceiver" >
            </receiver>

Here's what I have:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.tutorials.hp.alarmmanagerstarter">
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:theme="@style/AppTheme.NoActionBar">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

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

    </manifest>

Comments