简体   繁体   English

两项活动之间有趣的交流方式

[英]An interesting way of communication between two activities

The first step: 第一步:

public class MyHandler extends Application {
    private Handler handler = null;

    public Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

}

The next step: In activity A: 下一步:在活动A中:

MyHandler myHandler = (MyHandler)getApplication();
    Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            if(msg.what == 0x123)
                progressDialog.dismiss();
        }
    };
    myHandler.setHandler(handler);

In activity B: 在活动B中:

MyHandler myHandler = (MyHandler)getApplication();
Handler handler = myHandler.getHandler();
handler.sendEmptyMessage(0x123);

Although the reference of two myHandler is same, we use (MyHandler) to change Application to MyHandler.The Application has no field of handler,why can the Application keep the filed handler? 尽管两个myHandler的引用相同,但是我们使用(MyHandler)将Application更改为MyHandler。Application没有处理程序字段,为什么应用程序可以保留字段处理程序? Because I think in activity B, MyHandler myHandler = (MyHandler)getApplication(); 因为我认为在活动B中, MyHandler myHandler = (MyHandler)getApplication(); can't obtain the filed handler. 无法获取字段处理程序。

Polymorphism. 多态性。

The reference being of type Application doesn't necessarily mean that the referenced object is. 引用的类型为Application并不一定意味着引用的对象是。 The object could be Application or any subclass of Application . 该对象可以是Application或的任何子类Application

Writing (MyHandler) before a value is a cast , and simply converts the reference , not the object . (MyHandler)值之前是铸件 ,并且简单地转换基准 ,而不是对象 The validity of the cast is checked at runtime, and a ClassCastException will be thrown if the object is not MyHandler or a subclass thereof (in your case, the check passes, so it's no problem). 在运行时检查MyHandler的有效性,如果对象不是MyHandler或其子类,则抛出ClassCastException (在您的情况下,检查通过,因此没有问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM