Reputation: 5955
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?
Upvotes: 1
Views: 295
Reputation: 24740
you are getting a new Message by calling: Message.obtain(null, ...- this is why replyTo is null
Upvotes: 1