📜  获取来电号码 android 示例 (1)

📅  最后修改于: 2023-12-03 15:27:50.897000             🧑  作者: Mango

获取来电号码 Android 示例

在 Android 应用中,可以通过监听 Intent.ACTION_PHONE_STATE_CHANGED 广播来获取来电的相关信息,包括来电号码。本示例将演示如何通过监听来电广播获取来电号码。

步骤
  1. 创建 BroadcastReceiver 类,在 onReceive() 方法中处理来电广播,并获取来电号码。
public class PhoneStateReceiver extends BroadcastReceiver {
    private static final String TAG = "PhoneStateReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            Log.d(TAG, "Incoming call from: " + incomingNumber);
        }
    }
}
  1. 在 AndroidManifest.xml 文件中注册 BroadcastReceiver,同时添加权限获取。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <application
        ...
        <receiver android:name=".PhoneStateReceiver">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>
    </application>
</manifest>
  1. 在 Activity 中动态申请权限。
private static final int REQUEST_PERMISSION_READ_PHONE_STATE = 101;

if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
        != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
            REQUEST_PERMISSION_READ_PHONE_STATE);
} else {
    // 已经有权限,可以直接注册广播接收器
    registerPhoneStateReceiver();
}
  1. 在 onRequestPermissionsResult() 方法中处理授权结果,如果用户授权成功,则注册 BroadcastReceiver。
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSION_READ_PHONE_STATE) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 授权成功,可以直接注册广播接收器
            registerPhoneStateReceiver();
        }
    }
}

private void registerPhoneStateReceiver() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    registerReceiver(phoneStateReceiver, intentFilter);
}
结论

通过监听 Intent.ACTION_PHONE_STATE_CHANGED 广播,可以获取来电号码等来电相关信息。在使用时需要注意申请 READ_PHONE_STATE 权限,并动态申请权限。