[英]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. 通常,完成此任务需要3秒钟。
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. 并检查此消息的replyTo是否为空。 The replyTo is not null. replyTo不为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 . 它将调用方法update 。 In the handleMessage method, the replyTo is not null. 在handleMessage方法中,replyTo不为null。 However, after 3 seconds, in the update method, the replyTo is null, and it crashes. 但是,在3秒钟后,在update方法中,replyTo为null,并且崩溃。
Why is that? 这是为什么? probably, because the IncomingHandler is a static class? 可能是因为IncomingHandler是静态类? or what else reasons? 还是什么原因?
您通过调用以下命令获取新消息:Message.obtain(null,...-这就是为什么replyTo为null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.