Handler.Callback - 在从Handler实例化时更喜欢组合而不是继承

时间:2017-02-13 14:27:43

标签: android handler

我想知道使用Handler.Callback。我在网上找不到任何详细信息。在以下资源中: http://files.dcarl.me/books/First_Collection_Programming_Books/Asynchronous%20Android%20%5BeBook%5D.pdf 据说:

  

我们可以通过传递一个实例来优先考虑组合而不是继承   处理程序构造期间的Handler.Callback。

资源上的示例如下:

public static class SpeakHandler extends Handler {
    public static final int SAY_HELLO = 0;
    public static final int SAY_BYE = 1;
    public SpeakHandler(Callback callback) {
        super(callback);
    }
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what) {
            case SAY_HELLO:
                sayWord("hello"); break;
            case SAY_BYE:
                sayWord("goodbye"); break;
            default:
                super.handleMessage(msg);
        }
    }
    private void sayWord(String word) { … }
}
public static class Speaker implements Handler.Callback {
    public static final int SAY_WORD = 2;
    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == SAY_WORD) {
            sayWord((String)msg.obj);
            return true;
        }
        return false;
    }
    private void sayWord(String word) { … }
}
Handler h = new SpeakHandler(new Speaker());
h.sendMessage(Message.obtain(handler, Speaker.SAY_WORD, "!?"));

为什么我需要上面代码中的Handler.Callback?我可以做同样的事情:

    public static class SpeakHandler extends Handler {
    public static final int SAY_HELLO = 0;
    public static final int SAY_BYE = 1;
    public static final int SAY_WORD = 2;
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what) {
            case SAY_HELLO:
                sayWord("hello"); break;
            case SAY_BYE:
                sayWord("goodbye"); break;
            case SAY_WORD:
                sayWord((String)msg.obj); break;
            default:
                super.handleMessage(msg);
        }
    }
    private void sayWord(String word) { … }
}

什么是Handler.Callback?在官方文件中,据说

  

您可以在实例化Handler时使用回调接口来避免   必须实现自己的Handler子类。   我不明白这意味着什么......

0 个答案:

没有答案