另一个应用程序中的活动和服务之间的通信

时间:2013-06-15 20:59:07

标签: java android performance android-layout

我在活动和服务之间创建了一个通信(位于另一个应用程序中)。当我的服务从活动中获取调用时,它会生成一个新线程来执行任务。通常,完成此任务需要3秒钟。

当来自活动的消息进入服务时,我们持有它。并检查此消息的replyTo是否为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);

        }
}

任务完成后,它会通知托管它的类。它将调用方法更新。在 handleMessage 方法中,replyTo不为null。但是,在3秒之后,在更新方法中,replyTo为空,并且崩溃。

为什么?可能,因为IncomingHandler是一个静态类?或者还有什么原因?

1 个答案:

答案 0 :(得分:1)

你通过调用得到一条新消息:Message.obtain(null,...-这就是为什么replyTo为null