skip to Main Content

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

2

Answers


  1. If the API already exists, you don’t need a server. You just need to schedule a job to be done on the device every hour. You can use WorkScheduler for that. If the API needs to be written, then yes you need a server and need to learn how to write a web service. But that’s well beyond the size of a stack overflow question, you can google for a variety of tutorials on that.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search