简体   繁体   中英

Http Request in Android from the service

I am trying to do a post Http request from Service not from Activity. This Service is already been set to be continuously call after 5 second with the help of timertask.

In this service I am sending http request which is throwing error android.os.NetworkOnMainThreadException , I know why this error is thrown as I am sending http request from my main thread which is against android rules.

In Addition, I am aware I can use AsyncTask class, but the problem is AsyncTask class need to have UI thread which I do not have as I am in service.

May be another constraint I am having is the parent class is using calling this class in every 5 seconds so maybe some thread issue. Not sure.

So, can anybody suggest me some idea to perform this task, I am not sure if I can use Handlers for it, if so please give me simple example as I am bit out of touch from android.

If you need my code snippet let me know, but it is very straight just json HTTP request using httpclient.

public abstract class Data extends TimerTask {

protected void request(JSONObject content) {

     Log.i(TAG, content.toString());
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost httpost = new HttpPost("http://test.test.test/data.json");
        StringEntity se = new StringEntity(measurement.toString());
        httpost.setEntity(se);
        httpost.setHeader("Accept", "application/json");
        httpost.setHeader("Content-type", "application/json");
        ResponseHandler responseHandler = new BasicResponseHandler();
        client.execute(httpost, responseHandler);
    }catch(IOException exception){
        exception.printStackTrace();
    }
}

}

Here's a simple example from the android docs on creating a background service .The simplest way to accomplish what you're describing, a simple HttpPost from a background thread without using an AsyncTask is to use an IntentService .

public class BackgroundService extends IntentService {    

    @Override    
    protected void onHandleIntent(Intent workIntent) {   
        Bundle extras = workIntent.getExtras();
        if(extras != null){
           //do work here
        }
    }

}

The basic idea is pretty simple. Once your service is regiestered in your mainfest, you can start it, and send any data you need to it, using an Intent .

Intent startIntent = new Intent(this, BackgroundService.class);
startService.putExtra(stringMeasurmentToPost);
startService(startIntent);

This will broadcast the data to your IntentService , start it up, and perform whatever actions you need to on a background thread. If you're going to really be executing this every 5 seconds or so, you may way to look into using a regular service - not an intent service. The main difference between the two classes is that an IntentService will stop when it is finished doing whatever you will tell it to do, while a Service can remain active in the background so long as it is not killed by normal system processes. You can still send tasks to a Service using intents but the set up of a Service is slightliy more complicated than that of an IntentService .

Also - I would not use TimerTask . Rather I would use a Handler and Runnable combination with postDelayed() if you need to execute things repeatedly on a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM