How to receive a notification every hour if a condition is met on android studio?

Issue

Okay, I know my title can be confusing so I’ll explain a bit. I have access to an API and I would like that: every hour, my application, in the background, makes a request to this API and sends a notification if the API response contains a more or less recent date. To check if the answer is recent, I am already able to do it but what I would like to know is how to make this request in the background every hour and then how to send the data of this request in a notification (I already know how to create a notification, that’s not the problem). I’m stuck for some time, I imagine that the answer will be something related to a server, a domain that I know absolutely nothing about

Solution

You can try AlarmManager and BroadcastReceiver with the repeating time 1 hour

Example:

val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        } else PendingIntent.FLAG_UPDATE_CURRENT

val intent = Intent(context, YourReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, flag)
val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager

alarmManager.setRepeating(
        AlarmManager.RTC,
        timeInMillis,
        1000 * 60 * 60, //1h in millis
        pendingIntent
    )

Then write your YourReceiver and override onReceive function

class YourReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        //call api & check your requirements then push notification
    }
}

Manifest:

<application>
...
    <receiver android:name=".YourReceiver" />
</application>

Or you can try periodic work request:
https://medium.com/@sumon.v0.0/android-jetpack-workmanager-onetime-and-periodic-work-request-94ace224ff7d

Answered By – Man Ho

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published