# 如何实现 Android 挂断电话
## 整体流程
| 步骤 | 操作 |
| ---- | ---- |
| 1 | 获取电话管理器实例 |
| 2 | 注册广播接收器 |
| 3 | 监听电话状态改变 |
| 4 | 来电时挂断电话 |
## 操作步骤
1. 获取电话管理器实例
```java
// 获取电话管理器实例
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
- 注册广播接收器
// 创建广播接收器
BroadcastReceiver phoneStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 电话状态改变时的操作
}
};
// 注册广播接收器
registerReceiver(phoneStateReceiver, new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED));
- 监听电话状态改变
// 在广播接收器中监听电话状态改变
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
// 电话响铃时挂断电话
}
}
- 来电时挂断电话
// 挂断电话
try {
// 挂断电话的关键代码
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
Object iTelephony = m.invoke(tm);
Method endCallMethod = iTelephony.getClass().getDeclaredMethod("endCall");
endCallMethod.invoke(iTelephony);
} catch (Exception e) {
e.printStackTrace();
}
引用:以上是实现 Android 挂断电话的步骤,通过注册广播接收器监听电话状态改变,在电话响铃时挂断电话。
通过以上步骤,你就可以实现 Android 挂断电话的功能了。希望对你有所帮助,加油!