📅  最后修改于: 2023-12-03 15:27:50.897000             🧑  作者: Mango
在 Android 应用中,可以通过监听 Intent.ACTION_PHONE_STATE_CHANGED 广播来获取来电的相关信息,包括来电号码。本示例将演示如何通过监听来电广播获取来电号码。
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);
}
}
}
<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>
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();
}
@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 权限,并动态申请权限。