1

I am working on the code where i need to call some api for every 60*1000 milliseconds both in foreground and background independent of activity/fragment.

I have tried using handler and various other solutions like job scheduler etc.When device is connected to power source or device screen wakes my solution is working fine but when device gets locked it's not working perfectly. Currently i am using the below mentioned logic in application class

Handler minuteHandler = new Handler();
minuteHandler.postDelayed(runnable, 60*1000);
final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // method to call api
        minuteHandler.removeCallbacks(runnable);
        minuteHandler.postDelayed(runnable, 60*1000);
    }
};

The solution is simple as i need to call api for every 60*1000 milliseconds without lagging in milliseconds for upto 8 to 10 hours continuously until the app gets destroyed.

daedsidog
  • 1,732
  • 2
  • 17
  • 36
Prasanth
  • 217
  • 1
  • 2
  • 10
  • Your approach is fine but you have to protect it by using foreground service so the system doesn't kill your app's process. Oh, and you have to hold a wake lock during the whole time. This is going to drain the battery fast. – Eugen Pechanec Dec 27 '18 at 10:04
  • i also tried foreground service but when device gets locked i am getting time fluctuations in calling api – Prasanth Dec 27 '18 at 10:15

1 Answers1

1

One option is to use a wake lock. Here's an example from the docs:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();

// screen and CPU will stay awake during this section
wl.release();

This prevents screen locking

Or you can use the android:keepScreenOn for your Activity in AndroidManifest
Source: https://stackoverflow.com/a/3723649/9819031

Gourav
  • 2,746
  • 5
  • 28
  • 45