Android开发秘籍:用广播监听轻松搞定去电和来电
在Android开发中,你可以使用BroadcastReceiver来监听电话的拨入和拨出。以下是一个简单的示例: 首先,你需要在AndroidManifest.xml文件中注册你的BroadcastReceiver: ```xml <receiver android:name=".PhoneReceiver"> <intent-filter> <action android:name="android.intent.action.PHONE_STATE" /> </intent-filter> </receiver> ``` 然后,创建一个PhoneReceiver类: ```java public class PhoneReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.intent.action.PHONE_STATE")) { PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); switch (state) { case TelephonyManager.CALL_STATE_RINGING: // 来电 break; case TelephonyManager.CALL_STATE_OFFHOOK: // 拨出 break; case TelephonyManager.CALL_STATE_IDLE: // 挂断 break; } } }; TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); } } } ``` 在这个示例中,我们首先检查Intent的action是否为"android.intent.action.PHONE_STATE"。如果是,我们创建一个PhoneStateListener,并使用TelephonyManager的listen方法来监听电话的状态变化。当电话状态改变时,onCallStateChanged方法会被调用,我们可以根据state的值来判断是拨入、拨出还是挂断。 ######[AI写代码神器 | 367点数解答 | 2023-11-07 22:44:58]
- RealtimeMonitoringFragment 代码片段:Android 实时监控功能核心代码剖析(字节豆包 | 30点数解答 | 2024-10-12 10:31:18)294
- 揭秘:Android实时监控片段(RealTimeMonitoringFragment)代码实现(GPT | 531点数解答 | 2024-10-12 10:32:25)269
- AIDE编写Xposed软件:参考代码教你拦截Smail类方法名(阿里通义 | 649点数解答 | 2024-10-12 00:15:48)305
- 智能电话窗口按钮1弹起:获取坐标与手机IMEI码待处理(GPT | 208点数解答 | 2024-09-12 16:36:31)353
- Java 状态模式:模拟 TCP 连接多种状态及行为转换(GPT | 2147点数解答 | 2024-12-19 22:19:37)290
- Java实现状态模式:模拟TCP连接状态管理及行为处理(GPT | 1541点数解答 | 2024-12-19 22:19:57)279
- Android开发必知:android:layout_gravity与android:gravity的区别解析(阿里通义 | 299点数解答 | 2023-11-07 22:38:25)359
- Android开发必知:android:layout_gravity使用规则全解析(阿里通义 | 411点数解答 | 2023-11-07 22:38:52)377
- Android开发神器TypedArray:轻松读取XML资源属性的秘籍(阿里通义 | 347点数解答 | 2023-11-07 22:40:21)339
- Android开发必备:ContentProvider 全解析,优缺点大揭秘!(阿里通义 | 272点数解答 | 2023-11-07 22:40:32)369
- Android开发:发送短信必知的动态权限请求全流程 (阿里通义 | 380点数解答 | 2023-11-07 22:45:28)612
- 揭秘Android开发:从开源系统到应用发布的全流程(阿里通义 | 86点数解答 | 2023-11-07 22:46:19)341