nginx rewrite 1:监听Android手机的呼叫状态

来源:百度文库 编辑:中财网 时间:2024/05/03 10:05:07

开发应用程序的时候,我们希望能够监听电话的呼入,以便执行暂停音乐播放器等操作,当电话结束之后,再次恢复播放。在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;
   }
  }

 }

}