0

I need to execute periodic http requests. I use volley for the requests, but I don't want to overflow the queue.

Right now I've got a thread that enqueues the request and waits for 3 seconds.

AtomicBoolean quitUsersWatcher = new AtomicBoolean(false);

class UsersWatcher extends Thread {
    final Context context;
    ActiveUsersWatcher(Context c) {
        context = c;
    }
    public void run() {
        while (!quitUsersWatcher.get()) {
            JsonArrayRequest usersRequest = new JsonArrayRequest(Request.Method.GET, Config.ALL_USERS_URL, null,
                    this::getUsers,
                    Throwable::printStackTrace
            );

            try {
                RequestQueue queue = MySingleton.getInstance(context).getRequestQueue();
                queue.add(usersRequest);
                sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void getUsers(JSONArray jsonResult) {
        //some logic
    }
}

But I don't this that sleep is the best idea. I thought about a variable that increases by 1 up to 64 or 128 and then enqueues the request. Like this:

int counter = 0;
while (!quitUsersWatcher.get()) {
    if(counter >= 128) {
        JsonArrayRequest usersRequest = new JsonArrayRequest(Request.Method.GET, 
        Config.ALL_USERS_URL, null, 
        this::getUsers, 
        Throwable::printStackTrace);

        RequestQueue queue = MySingleton.getInstance(context).getRequestQueue();
        queue.add(usersRequest);
        counter = 0;
    }

    ++counter;        
}

But maybe there are some better tools to do something like this. I tried to search for a watcher, but I couldn't find anything useful.

How would you implement something like this?

Shout
  • 338
  • 5
  • 14

1 Answers1

1

You can either use WorkManager or Alarm Manager for calling the api repeatedly. Check this documentation on how to handle background tasks in Android.

Taranmeet Singh
  • 1,199
  • 1
  • 11
  • 14
  • I've already seen these. It says the WorkManager is for tasks that work even when app restarts, I don't need it. The Alarm Manager is for alarm clocks or calendar events. And the documentation is more about kotlin, but I've only took a quick look. Imma read it again and see how it go – Shout Jan 31 '22 at 11:29
  • @Shout the AlarmManager is also used for repeatable task. – Taranmeet Singh Jan 31 '22 at 11:38
  • Aight, I'll use the WorkManager, thanks! – Shout Jan 31 '22 at 12:09