Android监听来电和去电

要监听android打电话和接电话,只需下面2步骤
1.第一步,写一个Receiver继承自BroadcastReceiver

复制代码
 1 import android.app.Service;
 2 import android.content.BroadcastReceiver;
 3 import android.content.Context;
 4 import android.content.Intent;
 5 import android.telephony.TelephonyManager;
 6 import android.util.Log;
 7 
 8 public class PhoneStateBroadCastReceiver extends BroadcastReceiver
 9 {
10  private static final String TAG = "PhoneStateBroadCastReceiver";
11 
12  private static boolean mIncomingFlag = false;
13  private static String mIncomingNumber = null;
14 
15  @Override
16  public void onReceive(Context context, Intent intent)
17  {
18   // 如果是拨打电话
19   if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL))
20   {
21    mIncomingFlag = false;
22    String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
23    Log.i(TAG, "call OUT:" + phoneNumber);
24   } else
25   {
26    // 如果是来电
27    TelephonyManager tManager =
28    (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
29    switch (tManager.getCallState())
30    {
31    case TelephonyManager.CALL_STATE_RINGING:
32     mIncomingNumber = intent.getStringExtra("incoming_number");
33     Log.i(TAG, "RINGING :" + mIncomingNumber);
34     break;
35    case TelephonyManager.CALL_STATE_OFFHOOK:
36     if (mIncomingFlag)
37     {
38      Log.i(TAG, "incoming ACCEPT :" + mIncomingNumber);
39     }
40     break;
41    case TelephonyManager.CALL_STATE_IDLE:
42     if (mIncomingFlag)
43     {
44      Log.i(TAG, "incoming IDLE");
45     }
46     break;
47    }
48   }
49  }
50 
51 }
复制代码

第二步:在AndroidManifest.xml,配置写好的Receiver,并拦截相应的BroadCastAction,
另外注意加上相应的权限

复制代码
1 <receiver android:name=".broadcase.PhoneStateBroadCastReceiver"> 
2             <intent-filter>
3                <action android:name="android.intent.action.PHONE_STATE"/>          
4                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
5            </intent-filter>
6   </receiver>
7 <uses-permission android:name="android.permission.READ_PHONE_STATE" />
8 <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
复制代码

 Android监听来电和去电 | 若水工作室 http://www.92coding.com/blog/index.php/archives/46.html

本文转自欢醉博客园博客,原文链接http://www.cnblogs.com/zhangs1986/p/3243061.html如需转载请自行联系原作者


欢醉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值