Android监听来电状态

2022-12-19 13:43:02 浏览数 (2)

转载请以链接形式标明出处: 本文出自:103style的博客

记录一下.

代码语言:javascript复制
public class PhoneCallReceiver extends BroadcastReceiver {
    private static final String TAG = "PhoneCallReceiver ";
    private OnPhoneCallListener onPhoneCallListener;

    @Override
    public void onReceive(Context context, Intent intent) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
        int state = tm.getCallState();
        Logg.e(TAG, "state = "   state);
        if (onPhoneCallListener != null) {
            onPhoneCallListener.hasNewCall(state == TelephonyManager.CALL_STATE_RINGING);
        }
    }

    public void setOnOnPhoneCallListener(OnPhoneCallListener onPhoneCallListener) {
        this.onPhoneCallListener = onPhoneCallListener;
    }

    public interface OnPhoneCallListener {
        void hasNewCall(boolean valid);
    }
}
  • fragment or activity
代码语言:javascript复制
/**
 * 来电响铃的监听
 */
private PhoneCallReceiver phoneCallReceiver;
/**
 * 来电响铃监听是否已注册
 */
 private boolean hasRegisterPhoneCall = false;

// Activity
//@Override
//protected void onRestart() {
//    super.onRestart();
//    registerPhoneCallReceiver(true);
//}
@Override
public void onStart() {
    super.onStart();
    registerPhoneCallReceiver(true);
}
@Override
public void onStop() {
    super.onStop();
    registerPhoneCallReceiver(false);
}
/**
 * 监听来电响铃状态
 */
public void registerPhoneCallReceiver(boolean register) {
    if (register) {
        if (phoneCallReceiver== null) {
            phoneCallReceiver= new PhoneCallReceiver();
            phoneCallReceiver.setOnOnPhoneCallListener(valid -> {
                //
            });
        }
        if (!hasRegisterPhoneCall) {
            hasRegisterPhoneCall = true;
            activity.registerReceiver(phoneCallReceiver, new IntentFilter());
        }
    } else {
        if (phoneCallReceiver!= null && hasRegisterPhoneCall) {
            hasRegisterPhoneCall = false;
            activity.unregisterReceiver(phoneCallReceiver);
        }
    }
}
  • AndroidManifest.xml
代码语言:javascript复制
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<receiver android:name=".PhoneCallReceiver">
    <intent-filter android:priority="1000">
        <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
</receiver>

0 人点赞