Android 写一个接听电话和挂断电话的广播接收器
时间: 2024-05-03 09:23:14 浏览: 12
以下是一个简单的Android广播接收器示例,用于接听电话和挂断电话:
```java
public class PhoneCallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// 如果是电话呼入
if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
// 电话呼入时的操作
Log.d("PhoneCallReceiver", "Incoming call...");
}
}
// 如果是电话挂断
else if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
// 获取拨出电话号码
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
// 电话挂断时的操作
Log.d("PhoneCallReceiver", "Outgoing call ended...");
}
}
}
```
要使用该广播接收器,需要在AndroidManifest.xml文件中注册:
```xml
<receiver android:name=".PhoneCallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
```
这将使应用程序在电话呼入和电话挂断时收到广播。在PhoneCallReceiver类中,我们可以根据需要执行自己的操作,例如记录日志、显示通知等等。