打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
监听Android手机的呼叫状态

开发应用程序的时候,我们希望能够监听电话的呼入,以便执行暂停音乐播放器等操作,当电话结束之后,再次恢复播放。在Android平台可以通过TelephonyManager和PhoneStateListener来完成此任务。

 

TelephonyManager作为一个Service接口提供给用户查询电话相关的内容,比如IMEI,LineNumber1等。通过下面的代码即可获得TelephonyManager的实例。

  TelephonyManager mTelephonyMgr = (TelephonyManager) this
    .getSystemService(Context.TELEPHONY_SERVICE);

 

在Android平台中,PhoneStateListener是个很有用的监听器,用来监听电话的状态,比如呼叫状态和连接服务等。其方法如下所示:


public void onCallForwardingIndicatorChanged(boolean cfi)
public void onCallStateChanged(int state, String incomingNumber)
public void onCellLocationChanged(CellLocation location)
public void onDataActivity(int direction)
public void onDataConnectionStateChanged(int state)
public void onMessageWaitingIndicatorChanged(boolean mwi)
public void onServiceStateChanged(ServiceState serviceState)
public void onSignalStrengthChanged(int asu)

 

这里我们只需要覆盖onCallStateChanged()方法即可监听呼叫状态。在TelephonyManager中定义了三种状态,分别是振铃(RINGING),摘机(OFFHOOK)和空闲(IDLE),我们通过state的值就知道现在的电话状态了。

获得了TelephonyManager接口之后,调用listen()方法即可监听电话状态。

 

  mTelephonyMgr.listen(new TeleListener(),
    PhoneStateListener.LISTEN_CALL_STATE);

 

下面是个简单的测试例子,只是把呼叫状态追加到TextView之上。

package com.j2medev;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.TextView;

public class Telephony extends Activity {

 private static final String TAG = "Telephony";
 TextView view = null;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  TelephonyManager mTelephonyMgr = (TelephonyManager) this
    .getSystemService(Context.TELEPHONY_SERVICE);
  mTelephonyMgr.listen(new TeleListener(),
    PhoneStateListener.LISTEN_CALL_STATE);
  view = new TextView(this);
  view.setText("listen the state of phone\n");
  setContentView(view);
 }

 class TeleListener extends PhoneStateListener {

  @Override
  public void onCallStateChanged(int state, String incomingNumber) {
   super.onCallStateChanged(state, incomingNumber);
   switch (state) {
   case TelephonyManager.CALL_STATE_IDLE: {
    Log.e(TAG, "CALL_STATE_IDLE");
    view.append("CALL_STATE_IDLE " + "\n");
    break;
   }
   case TelephonyManager.CALL_STATE_OFFHOOK: {
    Log.e(TAG, "CALL_STATE_OFFHOOK");
    view.append("CALL_STATE_OFFHOOK" + "\n");
    break;
   }
   case TelephonyManager.CALL_STATE_RINGING: {
    Log.e(TAG, "CALL_STATE_RINGING");
    view.append("CALL_STATE_RINGING" + "\n");
    break;
   }
   default:
    break;
   }
  }

 }

}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
来电防火墙之呼叫转移实现的问题
android之通过phoneStateListener监听电话状态改变
android?电话状态的监听
侦听Android手机ServiceState
Android 直播打断事件处理
getSystemService详解
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服