Android 监听来电和去电状态

要实现监听到打电话和接电话的状态,需要用到广播接受者BroadcastReceiver,其实现代码请参考如下;

一、定义一个类,继承BroadcastReceiver,重写onReceive()方法。

 1 package com.example.phonereceiver;
 2 
 3 import android.app.Service;
 4 import android.content.BroadcastReceiver;
 5 import android.content.Context;
 6 import android.content.Intent;
 7 import android.telephony.TelephonyManager;
 8 
 9 public class PhoneReceiver extends BroadcastReceiver {
10 
11     @Override
12     public void onReceive(Context context, Intent intent) {
13         if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {//去电
14             System.out.println("去电");
15         } else {//来电(存在以下三种情况)
16             TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
17             switch (tm.getCallState()) {
18             case TelephonyManager.CALL_STATE_IDLE:
19                 System.out.println("挂断");
20                 break;
21             case TelephonyManager.CALL_STATE_OFFHOOK:
22                 System.out.println("接听");
23                 break;
24             case TelephonyManager.CALL_STATE_RINGING:
25                 System.out.println("响铃");
26                 break;
27             }
28         }
29     }
30 }

二、在清单文件中注册该广播,并加上相应的权限。

 1 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 2     package="com.example.phonereceiver"
 3     android:versionCode="1"
 4     android:versionName="1.0" >
 5 
 6     <uses-sdk
 7         android:minSdkVersion="8"
 8         android:targetSdkVersion="15" />
 9 
10     <uses-permission android:name="android.permission.READ_PHONE_STATE" />
11     <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
12 
13     <application
14         android:icon="@drawable/ic_launcher"
15         android:label="@string/app_name"
16         android:theme="@style/AppTheme" >
17         <receiver android:name=".PhoneReceiver" >
18             <intent-filter>
19                 <action android:name="android.intent.action.PHONE_STATE" />
20                 <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
21             </intent-filter>
22         </receiver>
23     </application>
24 
25 </manifest>

 

posted on 2014-04-22 17:41  清凉一夏之博客  阅读(1687)  评论(0编辑  收藏  举报