Wednesday, May 10, 2023

Daily#1. Using BroadcastReceivers for Alarm Functionality in Android Apps

In Android app development, one common way to implement alarm functionality is to use BroadcastReceiver. This allows your app to receive intents that are broadcast by other apps or the system itself, and take appropriate action based on those intents.

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Your custom alarm action here
    }
}
To set an alarm, use the AlarmManager system service, and set the appropriate PendingIntent to broadcast your custom intent:
private void setAlarm(long triggerAtMillis, Context context) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
}
Don't forget to register your BroadcastReceiver in the AndroidManifest.xml file:

<receiver android:name=".AlarmReceiver"/>

No comments:

Post a Comment

Learning Journey #6: Brief Exploration of Databases and its Management Systems

  Welcome to the "Learning Journey" series. This space is my personal archive where I share insights and discoveries from my explo...