android 获取呼出手机号码
时间: 2023-11-09 22:09:12 浏览: 81
Android获取手机号码
3星 · 编辑精心推荐
在 Android 中,可以通过监听系统广播来获取呼出手机号码。具体步骤如下:
1. 在 AndroidManifest.xml 文件中添加权限:
```xml
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
```
2. 创建一个 Broadcast Receiver,用于监听呼出电话:
```java
public class OutgoingCallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.d("OutgoingCallReceiver", "Phone number: " + phoneNumber);
}
}
}
```
3. 在 AndroidManifest.xml 文件中注册 Broadcast Receiver:
```xml
<receiver android:name=".OutgoingCallReceiver">
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
```
4. 在 Activity 或 Service 中启动 Broadcast Receiver:
```java
OutgoingCallReceiver receiver = new OutgoingCallReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
registerReceiver(receiver, filter);
```
这样当用户呼出电话时,Broadcast Receiver 就会接收到广播,并获取呼出的手机号码。
阅读全文