android 电话状态的监听(来电和去电) PhoneStateListener和TelephonyManager

来源:互联网 发布:win7网络修复大师 编辑:程序博客网 时间:2024/06/10 07:44

今天的程序可以实现电话状态改变时启动(来电、接听、挂断、拨打电话),但是暂时没法实现拨打电话时判断对方是否接听、转语音信箱等。Android在电话状态改变是会发送action为android.intent.action.PHONE_STATE的广播,而拨打电话时会发送action为android.intent.action.NEW_OUTGOING_CALL的广播,但是我看了下开发文档,暂时没发现有来电时的广播。知道这个就好办了,我们写个BroadcastReceiver用于接收这两个广播就可以了。
  1. package com.pocketdigi.phonelistener;
  1.  
  1. import android.app.Service;
  1. import android.content.BroadcastReceiver;
  1. import android.content.Context;
  1. import android.content.Intent;
  1. import android.telephony.PhoneStateListener;
  1. import android.telephony.TelephonyManager;
  1.  
  1. publicclassPhoneReceiverextendsBroadcastReceiver{
  1.  
  1. @Override
  1. publicvoid onReceive(Context context,Intent intent){
  1. // TODO Auto-generated method stub
  1. System.out.println("action"+intent.getAction());
  1. if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
  1. //如果是去电(拨出)
  1. System.out.println("拨出");
  1. }else{
  1. //查了下android文档,貌似没有专门用于接收来电的action,所以,非去电即来电
  1. System.out.println("来电");
  1. TelephonyManager tm =(TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
  1. tm.listen(listener,PhoneStateListener.LISTEN_CALL_STATE);
  1. //设置一个监听器
  1. }
  1. }
  1. PhoneStateListener listener=newPhoneStateListener(){
  1.  
  1. @Override
  1. publicvoid onCallStateChanged(int state,String incomingNumber){
  1. // TODO Auto-generated method stub
  1. //state 当前状态 incomingNumber,貌似没有去电的API
  1. super.onCallStateChanged(state, incomingNumber);
  1. switch(state){
  1. caseTelephonyManager.CALL_STATE_IDLE:
  1. System.out.println("挂断");
  1. break;
  1. caseTelephonyManager.CALL_STATE_OFFHOOK:
  1. System.out.println("接听");
  1. break;
  1. caseTelephonyManager.CALL_STATE_RINGING:
  1. System.out.println("响铃:来电号码"+incomingNumber);
  1. //输出来电号码
  1. break;
  1. }
  1. }
  1. };
  1. }
要在AndroidManifest.xml注册广播接收器:
  1. <receiverandroid:name=".PhoneReceiver">
  1. <intent-filter>
  1. <actionandroid:name="android.intent.action.PHONE_STATE"/>
  1. <actionandroid:name="android.intent.action.NEW_OUTGOING_CALL"/>
  1. </intent-filter>
  1. </receiver>
还要添加权限:
  1. <uses-permissionandroid:name="android.permission.READ_PHONE_STATE"></uses-permission>
  1. <uses-permissionandroid:name="android.permission.PROCESS_OUTGOING_CALLS"></uses-permission>


0 0