在android中检测传出呼叫和呼叫挂断事件

我有一个要求,其中我想要检测两种与Android调用有关的事件

  1. 无论何时打出电话,我的申请都应该与被叫号码一起了解这一点
  2. 当电话挂断(由于成功/失败),我的应用程序应该了解这个连同挂断的原因

这是可能的Android?

Solutions Collecting From Web of "在android中检测传出呼叫和呼叫挂断事件"

你应该创build一个BroadcastReceiver:

public class CallReciever extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals( TelephonyManager.EXTRA_STATE_RINGING)) { // Phone number String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); // Ringing state // This code will execute when the phone has an incoming call } else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals( TelephonyManager.EXTRA_STATE_IDLE) || intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals( TelephonyManager.EXTRA_STATE_OFFHOOK)) { // This code will execute when the call is answered or disconnected } } } 

你应该注册你的应用程序来听清这些意图:

 <receiver android:name=".CallReciever" > <intent-filter> <action android:name="android.intent.action.PHONE_STATE" /> </intent-filter> </receiver> 

有一个更简单的解决scheme,只使用TelephonyManager和PhoneStateListener.You甚至不必注册BroadcastReceiver。

 public class MyPhoneStateListener extends PhoneStateListener { @Override public void onCallStateChanged(int state, String incomingNumber) { switch (state) { //Hangup case TelephonyManager.CALL_STATE_IDLE: break; //Outgoing case TelephonyManager.CALL_STATE_OFFHOOK: break; //Incoming case TelephonyManager.CALL_STATE_RINGING: break; } } } 

并注册它:

 public static void registerListener(Context context) { ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE); } 

您需要为以下意向操作创build接收者:

  1. 拨出电话 – ACTION_NEW_OUTGOING_CALL
  2. 呼叫挂断 – ACTION_PHONE_STATE_CHANGED