1 point

How to use Alarm Manager in android?


Posted by @Awais malik #android #java

Step 0: first define an alarm manager veriable

    AlarmManager alarmManager;
content_copy Copy

Step 1: now initialize alarm manager

        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
content_copy Copy

Step 2: now we create an intent and will trigger it when time expires here it execute after three seconds

  final Intent intent = new Intent(ScheduleHold.this, AlarmReciever.class);
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
                            System.currentTimeMillis()+3000 , pendingIntent);
content_copy Copy

Step 3: Now you have to create a alarm receiver class which will listen when time expires

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

public class AlarmReciever extends BroadcastReceiver{

    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context,"Alarm Ring",Toast.LENGTH_SHORT).show();


content_copy Copy

Step 4: declare this alarm receiver in your manifest file like this

  <receiver android:name=".AlarmReciever"
content_copy Copy

Alarm manager in android is used to perform schedule tasks in this tutorial we will learn about how to use alarm manager with an example