X

Android tutorial on Alarm Manager || background task || alarm manager

 

In this blog on android alarm manager we will see how a alarm manager works.Now in a series we are discussing about the background services the way we handle them in android from past few blogs.

Let us go through android alarm manager  in now in general we know that alarm is a task of making us know that a particular time has arrived to do any task like early in the morning to wake up and so on..

Android alarm manager

In the same way we will provide our program with android alarm manager to let it know when to do a task by scheduling it.When ever we have to do any background task in android latest versions due to doze mode we can’t achieve it easily.

We have four ways in android alarm manager usage

1) RTC

2) RTC_WAKEUP

3) ELAPSED_REALTIME

4) ELAPSED_REALTIME_WAKEUP

 

We will be knowing the usage of android alarm manager and discuss these 4 types.

 

Android alarm manager project structure :

Android alarm manager project structure is shown for a easier implementation of structured coding practice.

 

Android alarm manager video tutorial :

 

activity_main.xml

Add two buttons to start alarms either one time or repetitive.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="horizontal"
    android:gravity="center"
    android:background="@android:color/darker_gray"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnOneTime"
        android:text="One Time Alarm"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:background="@android:color/white"
        android:layout_weight="1"/>

    <Button
        android:id="@+id/btnRepeating"
        android:text="Repeating Alarm"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:background="@android:color/black"
        android:textColor="@android:color/white"
        android:layout_weight="1"/>

</LinearLayout>

[/et_pb_text][et_pb_text admin_label=”Text” background_layout=”light” text_orientation=”left” use_border_color=”off” border_color=”#ffffff” border_style=”solid”]

 

AlarmNotificationReceiver.class

Create a alarm notification receiver class extending broadcast class so as to receive the alarm and perform a task on background.

public class AlarmNotificationReceiver extends BroadcastReceiver {

 

Inside on onReceive class make your declarations to be done i.e., task to be performed when alarm goes off.

@Override
public void onReceive(Context context, Intent intent) {
   
}

 

Now we will add a notification task for on Receive

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true)
        .setDefaults(Notification.DEFAULT_ALL)
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("Androidcoding.in")
        .setContentText("Alarm Testing Task")
        .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
        .setContentInfo("Info");

NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());

 

You may have your own declarations i am using a notification here as a example.

import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import androidx.core.app.NotificationCompat;

public class AlarmNotificationReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Androidcoding.in")
                .setContentText("Alarm Testing Task")
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
                .setContentInfo("Info");

        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1,builder.build());
    }
}

 

MainActivity.class

Initialize buttons in the view then we will start with android alarm manager object creation

val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

then intent and pending intent to handle the task

val myIntent: Intent
val pendingIntent: PendingIntent

 

myIntent = Intent(this@MainActivity, AlarmNotificationReceiver::class.java)
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0)

 

set the alarm

manager[AlarmManager.RTC, SystemClock.elapsedRealtime() + 10] = pendingIntent

 

RTC :

This alarm will not wake up your device when alarm goes off i.e, it will not make any action to trigger device but will wait till device wakes up and then updates the task details.

 

RTC WAKEUP :

This alarm will wake up your device once the alarm goes off.

 

ELAPSED REALTIME :

This alarm will count the time duration from boot including the sleep time and will not wake up device as RTC the difference from RTC is that the boot time.

 

ELAPSED REALTIME WAKEUP :

This alarm will count the boot time and device idle time to make the alarm, once the alarm goes off then it will wakeup the device rather than waiting for device to wake up.

 

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.SystemClock
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnOneTime.setOnClickListener {
            startAlarm(false)
        }

        btnRepeating.setOnClickListener {
            startAlarm(true)
        }
    }

    private fun startAlarm(isRepeat: Boolean) {
        val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val myIntent: Intent
        val pendingIntent: PendingIntent

        myIntent = Intent(this@MainActivity, AlarmNotificationReceiver::class.java)
        pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0)

        if (!isRepeat)
            manager[AlarmManager.RTC,
                    SystemClock.elapsedRealtime() + 10] = pendingIntent
        else
            manager.setRepeating(
                AlarmManager.RTC,
                SystemClock.elapsedRealtime() + 1000,
                10 * 1000.toLong(),
                pendingIntent
            )

    }
}

Android alarm manager output :

This screen depicts the usage of android alarm manager implementation.

 

 

If you like this tutorial on android alarm manager do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates.

abhishek:
Related Post

This website uses cookies.