Search code examples
androidandroid-asynctaskandroid-serviceandroidhttpclient

Android HTTP GET inside a Service Class


So I've been trying to GET responses from a URL inside a Android Service Class.

I've used an async task for the effect, that i can't get the asyncTask to .execute(), any idea why?

Keep in mind, this service runs every minute, even if aplication is not running.

Can I use a Service to GET responses from any URL, or I'm better off using the async task itself, if I can get it to execute?

So Im calling the asynctask

switch (mode) {
case ALL:
    new XMLRequestTask().execute(ABSOLUTE_WEBSERVICE_PATH + "all");
    Log.v(LOG_TAG, "XML requests, waiting for answer...");
    break;
case DELTA:
    new XMLRequestTask().execute(ABSOLUTE_WEBSERVICE_PATH + "delta");
    Log.v(LOG_TAG, "XML requests, waiting for answer...");
    break;
}

And

The task itself.

@Override
protected InputStream doInBackground(String... params) {
        Log.v(LOG_TAG, "Running background task");
    InputStream content = xmlDownloader.getXMlFromURL(mURL);
    //Log.v(LOG_TAG, "Running background task");
    return content;
    }   
@Override
    protected void onPostExecute(InputStream result) {
    Log.v(LOG_TAG, "XML Downloader got: " + result);
    //super.onPostExecute(result);
}

Thanks in advance for any help.

Best regards


Solution

  • Network operation should be handled in a background thread inside a Android Service. AsyncTask is responsible for updates in the UI.

    I think for your use case the encapsulation of all synchronization-specific stuff inside a sync adapter would be a good approach (http://udinic.wordpress.com/2013/07/24/write-your-own-android-sync-adapter/). Many cross-cutting concerns will be handled directly by the Android system. In combination with a CursorLoader you could update your ui each time the data has changed (http://developer.android.com/training/load-data-background/setup-loader.html).