Igor
Igor

Reputation: 1317

Initializing network connection in Service

I'm trying to implement Service to manage network in my app. This service would be used to communicate with an external server from several activities.

How and when should I initialize connection to the server? I thought about doing this in service's onCreate method like this:

@Override
public void onCreate() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try{
                socket = new Socket(HOST, PORT);

                ... 
            }
            catch(IOException e){
               // How to manage this exception?
            }
        }
    });
} 

But if connection error would occur how could I tell that to a client (activity which calls this service) ?

Upvotes: 0

Views: 135

Answers (1)

Diego Laballos
Diego Laballos

Reputation: 137

You should consider using an IntentService instead of Service.

You can override onHandleIntent(Intent) and do your network job there becouse it doesn't run on the main thread.

Android Developers Docs

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

To notify the activity about the Service response you can see a great example here

Also I would consider using an AsyncTaskLoader if you are going to use it in multiple activities and you're expecting a response.

Upvotes: 1

Related Questions