Android One Time / Repeat Alarm Example

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

1. Android Alarm Benefits.

  1. You can use the alarm to send a pending intent to invoke activity, service, or broadcast receiver. It can be one time call or call them in a set interval time repeatedly.
  2. An 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.
  3. An alarm can replace android background service which will run at all times. Because it can be triggered at a scheduled time so the alarm will only run at special times. This can reduce system resource costs.

2. How To Use Android Alarm.

2.1 Use Android Alarm Steps.

  1. First, you should get the android.app.AlarmManager instance uses the below code.
    AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
  2. Then create android.content.Intent instance with targeted component ( Activity, Service, or Broadcast Receiver ) class. And wrap the intent to an android.app.PendingIntent object.
    Intent intent = new Intent(getApplicationContext(), AlarmTriggerActivity.class);
    
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
  3. 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 one time or repeatedly.
    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTriggerTime, pendingIntent);
    
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime, alarmExecuteInterval, pendingIntent);

2.2 Android Alarm Set Method.

  1. set(int type,long startTime,PendingIntent pi): Set this alarm to execute for just one time. The parameter type is alarm type. The parameter startTime ( milliseconds ) is alarm execute time. The parameter pi is the alarm execute object ( activity, service, or broadcast receiver).
  2. setRepeating(int type,long startTime,long intervalTime,PendingIntent pi): Set the alarm to execute repeatedly within the intervalTime time. The parameter meaning is similar to the set method. The parameter 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 to the setRepeating method, the difference is the interval time is not fixed, it is random.
  4. The first parameter of the above method specifies the alarm type, it can be one of the below values.

2.3 Android Alarm Type Values.

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

3. Android Repeat Alarm Do Not Work Error.

  1. When you use repeat alarm, you may encounter the do not work error, this is because the interval time is too short or too long.
  2. Your alarm works properly indeed, but you can not see the effect. You had better use AlarmManager static interval variables instead, and you had better print the log to see the alarm execution status.
  3. 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 ( the below output messages ) in the android monitor log cat console output.
    Suspiciously short interval 10000 millis; expanding to 60 seconds

4. Android Alarm Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/aLjWrmOBmdM

  1. Click the first button, it will create a one-time alarm, it will open an activity when the alarm execute.
  2. The second button will create a repeat alarm, that alarm will invoke a background service for each execution time.
  3. The third button creates a repeat alarm also, but it will send a broadcast and run a broadcast receiver for each time.
  4. You can also see the logs in the android log cat monitor console.

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

5.1 Main Activity.

  1. 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.

  1. 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.

  1. AlarmTriggerService.java
    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.

  1. 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.

  1. 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.

  1. 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.

  1. 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>

References

  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

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.