简体   繁体   中英

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:

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:

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? Because I think in activity 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. The object could be Application or any subclass of Application .

Writing (MyHandler) before a value is a cast , and simply converts the reference , not the object . 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).

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