简体   繁体   中英

Communication between an activity and a service in another application

I created a communication between an activity and a service (is located in another application). When my service gets a call from the activity, it spawns a new thread to do a task. Normally, it takes 3 seconds to finish this task.

When the message from the activity comes to the service, we hold it. And check out whether the replyTo of this message is null or not. The replyTo is not null. (OK)

public class RemoteService extends Service{
    ...
    private static class IncomingHandler extends Handler implements Observer{       

        private Message msg;

        @Override
        public void handleMessage(Message msg){

            //- Hold the arrival message                        
            this.msg = msg;

            //- Check out value of replyTo
            Messenger replyTo = msg.replyTo;
            if (replyTo != null)
                Log.d("tag","replyTo ====///////==== null");
            else 
                Log.d("tag","replyTo ======== null");                                   

            //- Spawn a new thread to do the task   
            try{
                CustomThread thread = new CustomThread();
                thread.registerObserver(this);
                thread.start();
            }catch (Exception e) {
                log.d("tag",e.getMessage());
            }           
        }

        //- When the task is done
        @Override
        public void update(int result, String value) {

            //- Check out value of replyTo
            Messenger replyTo = msg.replyTo;
            if (replyTo != null)
                Log.d("tag","replyTo ====///////==== null");                           
            else 
                Log.d("tag","replyTo ======== null");

            //- prepare the data
            Bundle data = new Bundle();
            data.putString("key",value);
            Message message = Message.obtain(null,2,0,0);
            message.setData(data);

            //- Send message to the activity
            if (replyTo != null) replyTo.send(message);

        }
}

When the task is done, it notifies the class which hosts it. It will invoke the method update . In the handleMessage method, the replyTo is not null. However, after 3 seconds, in the update method, the replyTo is null, and it crashes.

Why is that? probably, because the IncomingHandler is a static class? or what else reasons?

您通过调用以下命令获取新消息:Message.obtain(null,...-这就是为什么replyTo为null

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