Android One Time / Repeat Alarm Example

Android alarm is a OS built-in service. It provide timer liked functions. With android alarm manager, you can create one time alarm, repeated alarm and so on. This article will tell you how to use it with examples.

1. Android Alarm Benefits.

You can use alarm to send a pending intent to invoke activity, service or broadcast receiver. It can be one time call, or call them in a setting interval time repeatedly.

Alarm can be used when the android device is sleep, they can wake up the device to execute your custom logic because it is a system level service.

Alarm can replace android background service which will run at all time. Because it can be triggered at scheduled time so alarm will only run at special time. This can reduce system resource cost.

2. How To Use Android Alarm.

First you should get android.app.AlarmManager instance use below code.

AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);

Then create a android.content.Intent instance with targeted component ( Activity, Service or Broadcast Receiver ) class. And wrap the intent to a android.app.PendingIntent object.

Intent intent = new Intent(getApplicationContext(), AlarmTriggerActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

Call AlarmManager’s set or setRepeating method to set the pending intent with the alarm object and start the alarm object. Then the alarm will be executed for one time or repeatedly.

alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTriggerTime, pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime, alarmExecuteInterval, pendingIntent);

Android Alarm Set Method.

  1. set(int type,long startTime,PendingIntent pi) : Set this alarm execute for just one time. type is alarm type. startTime ( milliseconds ) is alarm execute time. pi is the alarm execute object ( activity, service or broadcast receiver).
  2. setRepeating(int type,long startTime,long intervalTime,PendingIntent pi) : Set the alarm execute repeatedly with intervalTime time. The parameter meaning is similar with set method. intervalTime ( milliseconds ) is the duration between two alarm execution. It’s value can be AlarmManager.INTERVAL_DAY, INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_DAY, INTERVAL_HALF_HOUR, INTERVAL_HOUR. You can also specify your custom interval time in milliseconds.
  3. setInexactRepeating(int type,long startTime,long intervalTime,PendingIntent pi) : Similar with setRepeating method, the difference is the interval time is not fixed, it is random.

The first parameter of above method specify the alarm type, it can be one of below values.

Android Alarm Type Values.

  1. AlarmManager.ELAPSED_REALTIME : Alarm can not be executed when android device is sleep. This alarm use relative time(relative to os start up time).
  2. AlarmManager.ELAPSED_REALTIME_WAKEUP : Alarm will wake up device when android device is sleep. Use relative time also.
  3. AlarmManager.RTC : Alarm use absolute time ( current android os time ), this alarm will not be executed when device sleep.
  4. AlarmManager.RTC_WAKEUP : Similar with AlarmManager.RTC, the difference is this alarm is running even android os sleep, it will wake up android device when alarm run time is coming.

3. Android Repeat Alarm Do Not Work Error.

When you use repeat alarm, you may encounter do not work error, this is because the interval time is too short or too long.

READ :   How To Get Real File Path From Android Uri

Your alarm work properly indeed, but you can not see the effect. You had better use AlarmManager static interval variables instead, and you had better print log to see the alarm execution status.

If the repeat interval time is less than 60 seconds, then android os will expand it to 60 seconds by default, you can see this in android monitor log cat console output.

Suspiciously short interval 10000 millis; expanding to 60 seconds

repeat alarm interval time too short expanding to one minute4. Android Alarm Example.

android one time repeat alarm example

Click the first button, it will create a one time alarm, it will open an activity when the alarm execute.

The second button will create a repeat alarm, that alarm will invoke a background service for each execution time.

The third button create a repeat alarm also, but it will send a broadcast and run a broadcast receiver for each time.

You can also see log in android monitor log cat.

android alarm execution log

5. Alarm Start Activity, Service, Broadcast Receiver Example Source Code.

5.1 Main Activity.

AlarmManagerActivity.java

package com.dev2qa.example.alarm;

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

import com.dev2qa.example.R;

public class AlarmManagerActivity extends AppCompatActivity {

    public static final String ALARM_TYPE = "ALARM_TYPE";

    public static final String ALARM_TYPE_ONE_TIME = "ALARM_TYPE_ONE_TIME";

    public static final String ALARM_TYPE_REPEAT = "ALARM_TYPE_REPEAT";

    public static final String ALARM_DESCRIPTION = "ALARM_DESCRIPTION";

    private AlarmManager alarmManager = null;

    private PendingIntent pendingIntent = null;

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

        setTitle("dev2qa.com - Android Alarm Manager Example.");

        // Get system built-in alarm manager object.
        alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);

        // Click this button to start a one time alarm after 5 seconds from now.
        Button startOneTimeAlarmButton = (Button)findViewById(R.id.alarm_start_one_time_button);
        startOneTimeAlarmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Create an intent that will open an activity.
                Intent intent = new Intent(getApplicationContext(), AlarmTriggerActivity.class);
                // Add alarm type.
                intent.putExtra(ALARM_TYPE, ALARM_TYPE_ONE_TIME);
                // Add extra description string.
                intent.putExtra(ALARM_DESCRIPTION, "One time alarm start this activity.");
                // Wrap the intent object for later use to start the AlarmTriggerActivity.
                pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

                // Trigger alarm 5 seconds after now.
                long alarmTriggerTime = System.currentTimeMillis() + 5000;
                alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTriggerTime, pendingIntent);

                Toast.makeText(getApplicationContext(), "A one time alarm has been created, it will be triggered after 5 seconds. This alarm will open another activity.", Toast.LENGTH_LONG).show();
            }
        });

        // Click this button to start a repeated alarm, it will execute every interval seconds to invoke a service.
        Button startRepeatServiceAlarmButton = (Button)findViewById(R.id.alarm_start_repeat_service_button);
        startRepeatServiceAlarmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), AlarmTriggerService.class);
                intent.putExtra(ALARM_TYPE, ALARM_TYPE_REPEAT);
                intent.putExtra(ALARM_DESCRIPTION, "Repeat alarm start this service.");
                pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                long alarmStartTime = System.currentTimeMillis();
                long alarmExecuteInterval = 90*1000;

                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime, alarmExecuteInterval, pendingIntent);

                Toast.makeText(getApplicationContext(), "A repeat alarm has been created. This alarm will open a service.", Toast.LENGTH_LONG).show();
            }
        });

        // Click this button to start a repeated alarm, it will execute every interval seconds to send a broadcast.
        Button startRepeatBroadcastAlarmButton = (Button)findViewById(R.id.alarm_start_repeat_broadcast_button);
        startRepeatBroadcastAlarmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), AlarmTriggerBroadcastReceiver.class);
                intent.putExtra(ALARM_TYPE, ALARM_TYPE_REPEAT);
                intent.putExtra(ALARM_DESCRIPTION, "Repeat alarm start this broadcast.");
                pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                long alarmStartTime = System.currentTimeMillis();
                // This is too short, it will be expanded by android os to 60 seconds by default.
                long alarmExecuteInterval = 10*1000;
                alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime, alarmExecuteInterval, pendingIntent);

                Toast.makeText(getApplicationContext(), "A repeat alarm has been created. This alarm will send to a broadcast receiver.", Toast.LENGTH_LONG).show();
            }
        });

        // Click this button to cancel current pendingIntent related alarm.
        Button cancelRepeatAlarmButton = (Button)findViewById(R.id.alarm_cancel_repeat_button);
        cancelRepeatAlarmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alarmManager.cancel(pendingIntent);
                Toast.makeText(AlarmManagerActivity.this, "Cancel current alarm.", Toast.LENGTH_LONG).show();
            }
        });

    }
}

5.2 Alarm Started Activity.

AlarmTriggerActivity.java

package com.dev2qa.example.alarm;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import com.dev2qa.example.R;

public class AlarmTriggerActivity extends AppCompatActivity {

    private final static String TAG_ALARM_TRIGGER_ACTIVITY = "ALARM_TRIGGER_ACTIVITY";

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

        setTitle("dev2qa.com - Alarm Triggered Activity.");

        // Get intent that trigger this activity.
        Intent intent = getIntent();

        // Get alarm type.
        String alarmType = intent.getStringExtra(AlarmManagerActivity.ALARM_TYPE);

        // Get alarm description string.
        String alarmDescription = intent.getStringExtra(AlarmManagerActivity.ALARM_DESCRIPTION);

        TextView textView = (TextView)findViewById(R.id.alarm_trigger_activity_text_view);
        textView.setText(alarmDescription);

        Log.d(TAG_ALARM_TRIGGER_ACTIVITY, alarmDescription);

    }
}

5.3 Alarm Started Background Service.

package com.dev2qa.example.alarm;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class AlarmTriggerService extends Service {

    private final static String TAG_ALARM_TRIGGER_SERVICE = "ALARM_TRIGGER_SERVICE";

    public AlarmTriggerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        String message = "Alarm trigger this service. This is service onCreate() method.";
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        Log.d(TAG_ALARM_TRIGGER_SERVICE, message);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String alarmType = intent.getStringExtra(AlarmManagerActivity.ALARM_TYPE);
        String alarmDescription = intent.getStringExtra(AlarmManagerActivity.ALARM_DESCRIPTION);
        alarmDescription = alarmDescription + ", this is service onStartCommand() method/";

        Toast.makeText(getApplicationContext(), alarmDescription, Toast.LENGTH_LONG).show();

        Log.d(TAG_ALARM_TRIGGER_SERVICE, alarmDescription);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

5.4 Alarm Started Broadcast Receiver.

AlarmTriggerBroadcastReceiver.java

package com.dev2qa.example.alarm;

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

public class AlarmTriggerBroadcastReceiver extends BroadcastReceiver {

    private final static String TAG_ALARM_TRIGGER_BROADCAST = "ALARM_TRIGGER_BROADCAST";

    @Override
    public void onReceive(Context context, Intent intent) {
        String alarmType = intent.getStringExtra(AlarmManagerActivity.ALARM_TYPE);

        String alarmDescription = intent.getStringExtra(AlarmManagerActivity.ALARM_DESCRIPTION);

        Log.d(TAG_ALARM_TRIGGER_BROADCAST, alarmDescription);

        Toast.makeText(context, alarmDescription, Toast.LENGTH_LONG).show();

    }
}

5.5 Main Layout Xml File.

activity_alarm_manager.xml

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

    <Button
        android:id="@+id/alarm_start_one_time_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="One Time Alarm Start Activity"/>

    <Button
        android:id="@+id/alarm_start_repeat_service_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Repeat Alarm Start Service"/>

    <Button
        android:id="@+id/alarm_start_repeat_broadcast_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Repeat Alarm Start Broadcast"/>

    <Button
        android:id="@+id/alarm_cancel_repeat_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Cancel Repeat Alarm"/>
</LinearLayout>

5.6 Alarm Started Activity Layout Xml File.

activity_alarm_trigger.xml

<TextView
    android:id="@+id/alarm_trigger_activity_text_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="20dp"/>

5.7 Android Manifest Xml File.

AndroidManifest.xml

<activity android:name=".alarm.AlarmManagerActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

<activity android:name=".alarm.AlarmTriggerActivity" />

<service
    android:name=".alarm.AlarmTriggerService"
    android:enabled="true"
    android:exported="true" />

<receiver
    android:name=".alarm.AlarmTriggerBroadcastReceiver"
    android:enabled="true"
    android:exported="true"></receiver>

Reference

  1. Android Activity Example – Switch Between Screens
  2. Android Broadcast Overview
  3. How To Register Android BroadcastReceiver Statically
  4. How To Register BroadcastReceiver In Android Activity
  5. How To Create, Start, Stop Android Background Service
(Visited 103 times, 5 visits today)

Leave a Reply

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