Android Alarm Manager Example

Android allows you to access its alarm service using a class called AlarmManager. Using AlarmManager you can schedule to execute certain task at a particular time. Let us see an example of AlarmManger which executes a task  at a certain amount of user specified time.

1.Creating New Project

  1. Create a new project in Android Studio from File -> New Project
  2. Fill the required fields like Application name and package name and click Next
  3.  Select Basic activity and click Next, and click  Finish Button.A default activity will be created as MainActivity.java with layouts activity_main.xml and content_main.xml

2. Here is the code for your activity_main.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="codes4.com.alarmmanager.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

3.Next step is to add the code for content_main.xml. It will contain a layout with an EditText and a Button

content_main.xml

<?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="codes4.com.alarmmanager.MainActivity"
    tools:showIn="@layout/activity_main">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="vertical">

        <EditText
            android:id="@+id/ed_time"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:hint="Enter the number of seconds"
            android:inputType="numberDecimal" />

        <Button
            android:id="@+id/btn_set"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/ed_time"
            android:background="@color/colorPrimary"
            android:layout_marginTop="10dp"
            android:textColor="@color/white"
            android:text="Set" />

    </LinearLayout>
</RelativeLayout>

4. Next step is to create a class “AlarmBroadcastReciever.java” under java -> your package. which is a BroadcastReciever class which helps to start alarm

AlarmBroadcastReciever.java

package codes4.com.alarmmanager;
/**
 * Created by rameesfazal on 23/7/16.
 */
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.Toast;

public class AlarmBroadcastReceiver extends BroadcastReceiver {
    MediaPlayer mp;
    @Override
    public void onReceive(Context context, Intent intent) {
        Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        Ringtone ringtoneSound = RingtoneManager.getRingtone(context.getApplicationContext(), ringtoneUri);

        if (ringtoneSound != null) {
            ringtoneSound.play();
        }
        Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
    }
}

5.After that your need to register this BroadcastReciever class in AndroidManifest.xml. For that add the following
code to AndroidManifest.xml under your application tag.

<receiver android:name=".AlarmBroadcastReceiver"></receiver>

6.Here is the full code for AndroidManifest.xml

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="codes4.com.alarmmanager">

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

    <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=".AlarmBroadcastReceiver"></receiver>


    </application>

</manifest>

7.Finally Here is the code for MainActivity.Java

MainActivity.java

package codes4.com.alarmmanager;

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

public class MainActivity extends AppCompatActivity implements OnClickListener {

    Button btn_set;
    EditText ed_time;
    Toolbar toolbar;

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


        //method for initialisation
        init();

        btn_set.setOnClickListener(this);

    }

    private void init() {

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        btn_set = (Button) findViewById(R.id.btn_set);
        ed_time = (EditText) findViewById(R.id.ed_time);

    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.btn_set) {

            SetAlarm();

        }
    }

    public void SetAlarm() {
        int i = Integer.parseInt(ed_time.getText().toString());
        Intent intent = new Intent(this, AlarmBroadcastReceiver.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();
    }

}

Output

android_alarm_manager
android_alarm_manager
 

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

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