分享

android?电话状态的监听

 techres 2012-02-04

android 电话状态的监听

(2011-12-20 08:19:56)
标签:

杂谈


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

今天的程序可以实现电话状态改变时启动(来电、接听、挂断、拨打电话),但是暂时没法实现拨打电话时判断对方是否接听、转语音信箱等。Android在电话状态改变是会发送action为android.intent.action.PHONE_STATE的广播,而拨打电话时会发送action为android.intent.action.NEW_OUTGOING_CALL的广播,但是我看了下开发文档,暂时没发现有来电时的广播。知道这个就好办了,我们写个BroadcastReceiver用于接收这两个广播就可以了。


 package com.pocketdigi.phonelistener;
 
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
 
public class PhoneReceiver extends BroadcastReceiver {
 
 @Override
 public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub
  System.out.println("action"+intent.getAction());
  if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
   //如果是去电(拨出)
   System.out.println("拨出");
  }else{
   //查了下android文档,貌似没有专门用于接收来电的action,所以,非去电即来电
   System.out.println("来电");
   TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);  
   tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
   //设置一个监听器
  }
 }
 PhoneStateListener listener=new PhoneStateListener(){
 
  @Override
  public void onCallStateChanged(int state, String incomingNumber) {
   // TODO Auto-generated method stub
   //state 当前状态 incomingNumber,貌似没有去电的API
   super.onCallStateChanged(state, incomingNumber);
   switch(state){
   case TelephonyManager.CALL_STATE_IDLE:
    System.out.println("挂断");
    break;
   case TelephonyManager.CALL_STATE_OFFHOOK:
    System.out.println("接听");
    break;
   case TelephonyManager.CALL_STATE_RINGING:
    System.out.println("响铃:来电号码"+incomingNumber);
    //输出来电号码
    break;
   }
  }
 
 };
}

要在AndroidManifest.xml注册广播接收器:


         <receiver android:name=".PhoneReceiver">
   

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多