Call api for every 1 minute(60*1000 milliseconds) upto 10 hours

橙三吉。 提交于 2020-01-16 19:18:12

问题


I am working on the app that runs in background and need to call api for every 1 minute(60*1000 millisecond) without any fluctuations. I have tried Scheduler,timer and things but it is not working proper. For example, my scenario is to call the api on 09:11:36 am(first api call),09:12:36 am(second api call) and so on and at the end the final api call will be at 11:20:36 pm. I used below code :

Handler minuteHandler = new Handler();
minuteHandler.postDelayed(runnable, 60000);
final Runnable runnable = new Runnable() {
@Override
public void run() {
 // your runnable code
 minuteHandler.removeCallbacks(runnable);
 minuteHandler.postDelayed(runnable, 60000);
 }
};

and

new Timer("threadname", true).scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
   // your runnable code              
        }
    }, 0,60*1000);

etc., My question is that it is possible to achieve in android(all OS vesions).


回答1:


Try AlarmManager.setAlarmClock (API 21) or setExactAndAllowWhileIdle (API 23) with a foreground service. This is the only thing I found working in background in Android's Dose mode.

Please note, Handler stops when your activity is paused or stopped and resumes when activity is resumed.

Not sure about Timer. but, I am sure it won't work in background when device is sleeping.




回答2:


you can achieve that using service till api level 26 but in api level 27 service will automatically kill by the os.



来源:https://stackoverflow.com/questions/51558952/call-api-for-every-1-minute601000-milliseconds-upto-10-hours

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!