Search code examples
androidservicecronalarmmanagerschedule

android run service in background from time to time when the application is running


I am building an android app and when it is running I need to make a call to the my web server at each minute if the user is connected to a certain network.

I plan to use a service to make that call but how do I call it at each minute?. I think i need to use alaarm manager but where do I initalize it? in my start activity? I only need to execute the service when my app is running.

Thanks for your help.


Solution

  • If you want to call server only if app is running then no need to use alarm manager. there are other options like

    CoundDownTimer

    Thread

    I prefer CoundownTimer in that scenario and you can use like this

    CountDownTimer countDownTimer = new CountDownTimer(1000000, 60 * 1000) {
    
        @Override
        public void onTick(long millisUntilFinished) {
                // Do something on a tick.
        }
    
        @Override
        public void onFinish() {
            // Do something, maybe?
    
            this.start();
        }
    };
    countDownTimer.start();