简体   繁体   中英

Android: can a Thread spawned from a Service invoke one of the Service's methods directly?

I have a Service that spawns a Thread, which does some handshaking with a cloud service. When the Thread completes, it notifies the Service by explicitly dereferencing a method from an instance of the Service.

Question: in the Android model, is this acceptable? If not, what is the best practice with regard to the spawned Thread notifying the parent Service?

Note: I am using Lollipop (Android 5.0, API Level 21).

Here's the rough idea (borrowed from an example in one of the online Android books):

public class MyService extends Service {
    private static final String TOKEN = "msg-token";

    // XXX Implement Service methods here.

    private void notifyService(Object someObject) {
        // XXX Process result from cloud service interaction.
    }

    private class MyCloudClient implements Runnable {
        @Override
        public void run() {
            // XXX Interact with cloud service here.

            Bundle msgInfo = new Bundle();
            msgInfo.putSerializable(TOKEN, msgInfo);

            Message msg = Message.obtain();
            msg.setData(msgInfo);
            MyService.this.msgHandler.sendMessage(msg);        
        }
    }

    private Handler msgHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle msgInfo = msg.getData();
            Object someObject = msgInfo.getSerializable(TOKEN);
            MyService.this.notifyService(someObject);
        }
    };
}

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