Using an Android Service to handle a network connection

前端 未结 3 1639
误落风尘
误落风尘 2021-01-03 03:21

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 serve

3条回答
  •  旧时难觅i
    2021-01-03 03:52

    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

提交回复
热议问题