Android监听来电广播

AndroidBroadcastReceiver大约 1553 字

在Android上监听电话状态基本思路,注册接受电话状态的广播,接受广播即可。实现如下:

添加监听电话状态所需权限

注意权限检查

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />

接受电话状态的广播

public class PhoneStateReceiver extends BroadcastReceiver {  
    private static final String TAG = "PhoneStateReceiver";  

    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)) {// 摘机,通话状态  
            }  
        }  
    }  
}  

配置Receiver

在AndroidManifest.xml,配置写好的Receiver:

<receiver android:name=".PhoneReceiver" >  
    <intent-filter>  
        <action android:name="android.intent.action.NEW_OUTGOING_CALL" />  
        <action android:name="android.intent.action.PHONE_STATE" />  
    </intent-filter>  
</receiver>  
阅读 1042 · 发布于 2019-04-09

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批