Skip to content Skip to sidebar Skip to footer

How To Use Scheduler For Http Request

I want to create a application in Android that once it is installed in the deive.It send a HTTP rrequest in every 5 mins .After getting the response it shows the notification .How

Solution 1:

I created one Custom Thread class which will sleep for 5 secs.

publicclassSendHttpRequestThreadextendsThread {

    boolean sendHttpRequest;
    String userId;
    String pass;

    publicSendHttpRequestThread(String str1, String str2) {
        this.userId = str1;
        this.pass = str2;
        sendHttpRequest = true;
    }

    publicvoidstopSendingHttpRequest() {
        sendHttpRequest = false;
    }

    @Overridepublicvoidrun() {
        while (sendHttpRequest) {
            postRequest(userId, pass);
            //add code here to execute in background threadautoNotify();
            SystemClock.sleep(delayMillis);
        }
    }
}

I didn't implemented all code, you need to put inside while loop. Here delayMillis is integer value holding 5000 as sleep() takes input of mili seconds.

To execute this Thread, write following code.

sendHttpRequestThread = newSendHttpRequestThread("Test","Test");
sendHttpRequestThread.start();

To stop this Thread, write following code.

sendHttpRequestThread.stopSendingHttpRequest();

If you want to stop this thread when activity is stopped, then write like below.

@OverrideprotectedvoidonStop() {
    sendHttpRequestThread.stopSendingHttpRequest();
    super.onStop();
}

Solution 2:

Replace below code in onCreate() method

privateTimerrefresh=null;
    privatefinallongrefreshDelay=5 * 1000;

            if (refresh == null) { // start the refresh timer if it is null
                refresh = newTimer(false);

                Datedate=newDate(System.currentTimeMillis()+ refreshDelay);
                refresh.schedule(newTimerTask() {

                        @Overridepublicvoidrun() {
                             postHttpRequest("Test","Test");
                            refresh();
                        }
                    }, date, refreshDelay);

Post a Comment for "How To Use Scheduler For Http Request"