使用方法引用定义BroadcastReceiver.onReceive

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用方法引用定义BroadcastReceiver.onReceive相关的知识,希望对你有一定的参考价值。

使用Jack支持Java 8,我希望能够写出类似的东西:

public void onReceive(Context context, Intent intent) {
    if (!intent.getAction().equals(ACTION_BINGO)) return;
    Log.d(TAG, "Bingo!");
}

... 

registerReceiver(this::onReceive, INTENT_FILTER_BINGO);

不幸的是,这是不可能的。虽然onReceive()BroadcastReceiver的独特抽象方法,但该东西不是一个接口,它是一个抽象类,看起来似乎不能被lambda表达式替换。有什么建议可以解决这个问题吗?

答案

使用this answer中概述的技巧,这是我得到的:

public class BroadcastReceiver extends android.content.BroadcastReceiver {

    private final BiConsumer<Context, Intent> receiver;

    public BroadcastReceiver(final BiConsumer<Context, Intent> onReceive) {
        receiver = onReceive;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (receiver == null) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
        receiver.accept(context, intent);
    }
}

不像我预期的那样简洁,但更好:

BroadcastReceiver receiver = new BroadcastReceiver(this::onReceive);
registerReceiver(receiver, INTENT_FILTER_BINGO);
另一答案

只是为了扩展上面的答案,没有BiConsumer(不适用于API <24)

interface IBR {
    void onReceive(Context context, Intent intent);
}

class BroadcastReceiver extends android.content.BroadcastReceiver {
    private final IBR receiver;

    public BroadcastReceiver( IBR receiver ){
        this.receiver = receiver;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        receiver.onReceive(context, intent);
    }
}

以上是关于使用方法引用定义BroadcastReceiver.onReceive的主要内容,如果未能解决你的问题,请参考以下文章

如何使用CONNECTIVITY_CHANGE定义Broadcastreceiver?

在单例中使用 BroadcastReceiver 的最巧妙方法等等

android 自定义视图中能不能定义BroadcastReceiver

BroadcastReceiver peekService() 返回 null

BroadcastReceiver广播相关 - 转

Android——BroadcastReceiver广播机制(自定义广播)