自定义BroadcastReceiver构造函数不起作用

时间:2016-08-15 13:10:12

标签: java android

我在Android中定义了一个BroadcastReceiver。这样的代码。

public static class DataReceiver extends BroadcastReceiver{

    private Handler handler;

    public DataReceiver(){

    }

    public DataReceiver(Handler handler){
        this.handler = handler;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        OutputData outputData = (OutputData) intent.getSerializableExtra("OutputData");
        Message msg = new Message();
        msg.obj = outputData;
        handler.sendMessage(msg);
    }
}

然后我在Activity中初始化BroadCastReceiver并像这样注册它

DataReceiver mReceiver = new DataReceiver(new Handler(){
    @Override
    public void handleMessage(Message msg) {
        OutputData outputData = (OutputData) msg.obj;
        updateUI(outputData);
    }
});

@Override
protected void onResume() {
    super.onResume();
    IntentFilter intentFilter = new IntentFilter();
    registerReceiver(mReceiver,intentFilter);
}

当我在Service中发送广播时,它会像这样引发NullPointException

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Handler.sendMessage(android.os.Message)' on a null object reference

它说onReceive方法中的处理程序是null。但是我在构造函数中已经有了初始处理程序。为什么会这样。

0 个答案:

没有答案