简体   繁体   中英

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) ?

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.

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