简体   繁体   中英

Using an Android Service to handle a network connection

I'm working on an Android app that needs to maintain a network connection to a chat server. I understand that I can create a service to initiate the connection to the server, but how would the service notify an Android Activity of new incoming messages? The Activity would need to update the view to show the new messages. I'm pretty new to Android, so any help is appreciated. Thanks!

Can you pass a handler to your service?

First, define your handler as an interface. This is an example, so yours may be more complex.

public interface ServerResponseHandler {

    public void success(Message[] msgs); // msgs may be null if no new messages
    public void error();

}

Define an instance of your handler in your activity. Since it's an interface you'll provide the implementation here in the activity, so you can reference the enclosing activity's fields and methods from within the handler.

public class YourActivity extends Activity {

// ... class implementation here ...

    updateUI() { 
        // TODO: UI update work here
    }

    ServerResponseHandler callback = new ServerResponseHandler() {

        @Override
        public void success(Message[] msgs) {
            // TODO: update UI with messages from msgs[]

            YourActivity.this.updateUI();
        }

        @Override
        public void error() { 
            // TODO: show error dialog here? (or handle error differently)
        }

    }

    void onCheckForMessages() { 
        networkService.checkForMessages(callback);
    }

and NetworkService would contain something like:

void checkForMessages(ServerResponseHandler callback) { 

    // TODO: contact server, check for new messages here

    // call back to UI
    if (successful) { 
        callback.success(msgs);
    } else {
        callback.error();
    }
}  

Also, as Aleadam says, you should also be away that a service runs on the same thread by default. This is often not preferred behavior for something like networking. The Android Fundamentals Page on Services explicitly warns against networking without separate threads:

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

For more information on using threads in your service, check out the SO articles Application threads vs Service threads and How to start service in new thread in android

One common and useful approach is to register a broadcast receiver in your Activity, and have the Service send out notification events when it has useful data. I find this to be easier to manage than implementing a handler via a callback, mainly because it makes it easier and safer when there is a configuration change. If you pass a direct Activity-reference to the Service then you have to be very careful to clear it when the Activity is destroyed (during rotation, or backgrounding), otherwise you get a leak.

With a Broadcast Receiver you still have to unregister when the Activity is being destroyed, however the Service never has a direct reference to the Activity so if you forget the Activity will not be leaked. It is also easier to have the Activity register to listen to a topic when it is created, since it never has to obtain a direct reference to the Service...

Lars Vogel's article discusses this approach, it is definitely worth reading! http://www.vogella.com/tutorials/AndroidServices/article.html#using-receiver

Did you check the Service API page: http://developer.android.com/reference/android/app/Service.html ?
It has a couple of examples on how to interact with a Service.

The service runs on the same thread and the same Context as the Activity. Check also here: http://developer.android.com/reference/android/content/Context.html#bindService%28android.content.Intent,%20android.content.ServiceConnection,%20int%29

Finally, take a look also at Lars Vogel's article: http://www.vogella.de/articles/AndroidServices/article.html

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