user2728033
user2728033

Reputation: 61

Static block in intent service throws NetworkOnMainThreadException

have created a IntentService, in which I have created a static block in which I am doing some net related work, On which it is giving NetworkOnMainThreadException: Code looks like :

public class XService extends IntentService {
    static {
        //Net related work 
        //on executing this gives NetworkOnMainThreadException
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        //Doing my work here
    }   
}

How can this throw NetworkOnMainThreadException when IntentSrevice run on separate thread?

Please help and thanks in advance.

Upvotes: 1

Views: 223

Answers (2)

divinemaniac
divinemaniac

Reputation: 277

You should do the net related work you want to do inside OnHandleIntent() as this method runs on a separate thread.

Where you are putting the net related work now runs on the main thread.

Upvotes: 0

Sourabh Bans
Sourabh Bans

Reputation: 3134

This happens because you are doing a network operation on the main thread, and this is not allowed on Android 3.0 and above. Even though it is in a service, services are run on the UI thread unless you specifically launch them in another thread or create a thread inside it.

You can fix this by running the task in a service off the main UI thread, by using a Thread or an AsyncTask.

Try creating a new thread in onStartCommand()

Or you can do something like...

new Handler().post(new Runnable() { 
@Override public void run() {
 getData(); 
} });

Upvotes: 1

Related Questions