侦听器始终为null

时间:2019-06-21 19:34:50

标签: android broadcastreceiver

我有这样的广播接收器

public class PhoneCallStateReceiver extends BroadcastReceiver {
private static boolean incomingFlag = false;
private OnCallListener mListener;
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
        incomingFlag = false;
        mListener.startCall();
    } else {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
        switch (tm.getCallState()) {
            case TelephonyManager.CALL_STATE_RINGING:
                mListener.startCall();
                incomingFlag = true;
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                if (incomingFlag) {
                    mListener.stopCall();
                }
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                if (incomingFlag) {
                    mListener.stopCall();
                    Log.i(TAG, "incoming IDLE");
                }
                break;
        }
    }
}

public void setOnCallListener(OnCallListener listener) {
    this.mListener = listener;
}

interface OnCallListener {
    void startCall();
    void stopCall();
}

}

在我的活动代码中

mPhoneCallStateReceiver = new PhoneCallStateReceiver();
    mPhoneCallStateReceiver.setOnCallListener(this);
    registerReceiver(mPhoneCallStateReceiver, new IntentFilter("android.intent.action.PHONE_STATE"));

但是当调用进入类方法时,调用mListener.startCall();。 并在这些行中出现错误null对象 我该如何解决?

0 个答案:

没有答案