Android developmentAndroid tutorial

How to use Alarm Manager and Broadcast Receiver in Android

In this Android Atrical, How to use Alarm Manager and Broadcast Receiver in Android. here I have also used an android service for creating an android Alarm Tutorial for android development. and also show android alarm notifications. here I am user android background service and android Broadcast receiver to start an alarm.

Android Service:- Android service is a component that is used to perform operations on the background.

 Alarm Manager and Broadcast Receiver in Android.

AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, MyAlarmReceiver.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
int interval = 5000; 
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

 Android different types of Alarm Manager :

setInExactAndRepeating – This doesn’t trigger the alarm at the exact time.
setExact – Setting an alarm manager using this ensures that the OS triggers the alarm on the exact time.
setExactAndAllowWhileIdle – This method can be used with Android 6 M. These alarms are allowed to get executed even in low power modes.

Let,s Start On Development Of Example.

  • Add permission and service in AndroidManifest.xml.
  • Android Create UI For Alarm App two-button Start and Stop.
  • Start a Server and mange in home.java class.
  • Create a MyBroadcastReceiver.java class 

 

Step: 1  Add permission and service in AndroidManifest.xml

firstly you can add android user permission in android app for an alarm App. used a receive boot completed user permission in Android manifest file.

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".HomeActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver
            android:name=".MyBroadCastReceiver"
            android:directBootAware="true"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <service
            android:name="com.codeplayon.alarmapp.MyService"
            android:enabled="true"
            android:exported="false"
            android:process=":remote" />
    </application>
</manifest>

Step 2: Create a UI  activity_home.XML For Alarm App two-button Start and Stop.

create an android UI screen to strat alarm and stop. you can be used a two-button his name start and stop alarm.

 <Button
        android:id="@+id/btnStartAlarm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Alarm"
       />

    <Button
        android:id="@+id/btnCancelAlarm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Alarm"
       />

Step 3: Add these code in the home.java class.

in your home java class implement your UI button and call the android service and create an alarm service for show a notification and set a time of alarm and run these service on button click and stope service on button click.

public class HomeActivity extends AppCompatActivity {

    Button btnStartAlarm, btnCancelAlarm;

    AlarmManager alarmManager;
    PendingIntent pendingIntent;

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

        btnStartAlarm = findViewById(R.id.btnStartAlarm);
        btnCancelAlarm = findViewById(R.id.btnCancelAlarm);

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

        Intent alarmIntent = new Intent(this, MyBroadCastReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

        btnStartAlarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAlarm();
            }
        });

        btnCancelAlarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancelAlarm();
            }
        });
    }

    private void startAlarm() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
        }


    }

    private void cancelAlarm() {
        alarmManager.cancel(pendingIntent);
        Toast.makeText(getApplicationContext(), "Alarm Cancelled", Toast.LENGTH_LONG).show();
    }
}

 

Step 4: Android make a MyBroadcastReceiver.java class.

in this java class, you can create a broadcast receiver to run your alarm service. for android alarm manger.

public class MyBroadCastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null && intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
    Intent serviceIntent = new Intent(context, MyService.class);
    context.startService(serviceIntent);
} else {
    Toast.makeText(context.getApplicationContext(), "Hi codeplayon", Toast.LENGTH_LONG).show();
}
}

 Step 5: Create an android java class  MyService.java.

in this java class, you can be used an android background service. this service runs on your phone background. when your App is not run on a phone.

public class MyService extends IntentService {


    public MyService() {
        super("MyService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

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

        Intent alarmIntent = new Intent(this, MyBroadCastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, 0, 5000, pendingIntent);
    }
}