监听手机电话状态改变的两种方法

监听电话状态需要权限


方式一:

public class PhoneReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("action" + intent.getAction());
        //如果是去电
        if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
            String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        } else {
            //非去电即来电.
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
            tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    }

    PhoneStateListener listener = new PhoneStateListener() {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            //注意,方法必须写在super方法后面,否则incomingNumber无法获取到值。
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    System.out.println("响铃:来电号码" + incomingNumber);
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    System.out.println("接听");
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    System.out.println("挂断");
                    break;
            }
        }
    };
}


方式二:


public class PhoneReceiver extends BroadcastReceiver {  
    private static final String TAG = "PhoneReceiver";  
  
    public void onReceive(Context context, Intent intent) {  
        Log.i(TAG, "onReceive()");  
        String action = intent.getAction();  
  
        if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) {// 去电  
            String outNumber = this.getResultData();// 去电号码  
        } else if ("android.intent.action.PHONE_STATE".equals(action)) {// 来电  
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);  
            String inNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);// 来电号码  
            if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) {// 电话正在响铃  
            } else if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)) {// 挂断  
            } else if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK)) {// 摘机,通话状态  
            }  
        }  
    }  
} 

清单文件注册:

  
      
          
          
      
  

两者区别 : 方式一会接收到多次广播,方式二根据状态只会接收到一次,多次广播有可能影响到判断标识位,有需要时可以考虑第二种方式。
电话状态图:

监听手机电话状态改变的两种方法_第1张图片



你可能感兴趣的:(Android)