Skip to content Skip to sidebar Skip to footer

Android: How To Send Http Request Via Service Every 10 Seconds

I need to receive a status from the server every 10 seconds. I tried to do that by sending a http request via service. The problem is that my code executes only once. This is the c

Solution 1:

Put a handler inside onPostExecute to send a http request after 10 secs

new Handler().postDelayed(new Runnable() {
        public void run() {
            requestHttp();
        }
    }, 10000);

After 10 secs doInBackground will be executed again, after that onPostExecute again, handler again and so on and so on..

Solution 2:

You can simply use CountDownTimer class in android.

publicclassAlertSessionCountDownTimerextendsCountDownTimer {

    publicAlertSessionCountDownTimer(long startTime, long interval) {
        super(startTime, interval);
    }

    @OverridepublicvoidonFinish() {
        //YOUR LOGIC ON FINISH 10 SECONDS
    }

    @OverridepublicvoidonTick(long millisUntilFinished) {
        //YOUR LOGIC ON TICK
    }
}

Hope it will help you.

Solution 3:

The reason the code only runs once is that there's a return in your timer loop. However, I'd advise moving the loop to your background task or using one of the other answers given here rather than implementing a loop in onStartCommand() that never returns.

Solution 4:

Handlerhandler_proc=newHandler();

finalRunnablerunnable_proc=newRunnable() {
    publicvoidrun() {
        requestHttp(newOnFinish() {
            @OverridepublicvoidonSuccess() {
                // pause should be considered since the end of the previous http request.// Otherwise, new requests will occur before the previous one is complete,// if http_timeout > delay
                handler_proc.postDelayed(runnable_proc, 10000);
            }
        });
    }
}

handler_proc.post(runnable_proc);

Solution 5:

put return START_STICKY; after while , and service will work properly

Post a Comment for "Android: How To Send Http Request Via Service Every 10 Seconds"