android9.0源码来电屏蔽

首先,通过获取TelephonyManage,第二继承PhoneStateListener 监听电话状态的变化,执行判断
哪个地方需要此功能加registerphone(this||***.this)

 public void registerphone(Context context) {
    
     mPhoneStateListener = new PhoneCallListener(); //监听
    
    mTelephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); //获取TelephonyManager
     
     mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); //listen执行

 }	
public class PhoneCallListener extends PhoneStateListener { //继承PhoneStateListener 
    public void onCallStateChanged(int state, String incomingNumber) {
        Log.d(TAG, "onCallStateChanged-state: " + state); //打印LOG
        Log.d(TAG, "onCallStateChanged-incomingNumber: " + incomingNumber);
        switch (state)  { //执行判断
            case TelephonyManager.CALL_STATE_RINGING: //电话状态
                 endCall(); //挂断
                break;
            default:
                break;
        }
        super.onCallStateChanged(state, incomingNumber);
    }
}

private void endCall() {
    try {
       mTelephonyManager.endCall();    //调用mTelephonyManager中的endCall()进行挂断
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(TAG, "endCallError", e);
    }
}

取消来电屏蔽

@Override

protected void onDestroy() {
    
    super.onDestroy();
	
	mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);

	
}

在需要的地方的onDestroy中加入

附贴listen()

 public void listen(PhoneStateListener listener, int events) {
   
    if (mContext == null || listener == null) return;
   
    try {
        
        boolean notifyNow = (getITelephony() != null);
        
        // If the listener has not explicitly set the subId (for example, created with the
       
        // default constructor), replace the subId so it will listen to the account the
       
        // telephony manager is created with.
       
        if (listener.mSubId == null) {
       
            listener.mSubId = mSubId;
     
        }

        ITelephonyRegistry registry = getTelephonyRegistry();
        if (registry != null) {
            registry.listenForSubscriber(listener.mSubId, getOpPackageName(),
                    listener.callback, events, notifyNow);
        } else {
            Rlog.w(TAG, "telephony registry not ready.");
        }
    } catch (RemoteException ex) {
        // system process dead
    }
}

PhoneStateListener.LISTEN_NONE值

           public static final int LISTEN_NONE = 0;

猜你喜欢

转载自blog.csdn.net/weixin_41422638/article/details/102636262