Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 code for my service:

public class ServiceStatusUpdate extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    while(true)
    {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            new DoBackgroundTask().execute(Utilities.QUERYstatus);
            e.printStackTrace();
        }
        return START_STICKY;            
    }
}

private class DoBackgroundTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        String response = "";
        String dataToSend = params[0];
        Log.i("FROM STATS SERVICE DoBackgroundTask", dataToSend);
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(Utilities.AGENT_URL);

        try {
            httpPost.setEntity(new StringEntity(dataToSend, "UTF-8"));

            // Set up the header types needed to properly transfer JSON
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept-Encoding", "application/json");
            httpPost.setHeader("Accept-Language", "en-US");

            // Execute POST
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity responseEntity = httpResponse.getEntity();
            if (responseEntity != null) {
                response = EntityUtils.toString(responseEntity);
            } else {
                response = "{\"NO DATA:\"NO DATA\"}";
            }
        } catch (ClientProtocolException e) {
            response = "{\"ERROR\":" + e.getMessage().toString() + "}";
        } catch (IOException e) {
            response = "{\"ERROR\":" + e.getMessage().toString() + "}";
        }
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        Utilities.STATUS = result;
        Log.i("FROM STATUS SERVICE: STATUS IS:", Utilities.STATUS);
        super.onPostExecute(result);
    }
}
}

Thank's alot Avi

like image 908
אVי Avatar asked Oct 27 '13 11:10

אVי


2 Answers

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..

like image 181
null Avatar answered Oct 19 '22 19:10

null


You can simply use CountDownTimer class in android.

public class AlertSessionCountDownTimer extends CountDownTimer {

    public AlertSessionCountDownTimer(long startTime, long interval) {
        super(startTime, interval);
    }

    @Override
    public void onFinish() {
        //YOUR LOGIC ON FINISH 10 SECONDS
    }

    @Override
    public void onTick(long millisUntilFinished) {
        //YOUR LOGIC ON TICK
    }
}

Hope it will help you.

like image 29
Rushabh Patel Avatar answered Oct 19 '22 20:10

Rushabh Patel