仅捕获Android中的来电

时间:2013-10-28 12:08:41

标签: android android-intent broadcastreceiver android-broadcast

我正在创建一个应用,只需要捕获来电。我正在使用BroadCast类和Phone Listener类,并在PhoneListnere类中捕获是否有来电。我的问题是,如果有任何拨出电话,我不希望我的应用程序被触发。即使有任何传出呼叫,我的广播类也会触发(虽然我整齐地退出应用程序以进行传出呼叫),但并不喜欢应用程序实际上正在被触发的想法。是否有任何特定的Intent来处理来电?

1 个答案:

答案 0 :(得分:0)

您可以使用ACTION_PHONE_STATE_CHANGED意图,并存储最后一个状态。如果当前状态为TelephonyManager.EXTRA_STATE_OFFHOOK,则存在拨号,活动或保持的呼叫。如果之前的状态是RINGING,则这是来电。如果之前的状态是IDLE,则这是一个拨出电话。

以下接收器区分不同的场景:

public void onReceive(Context context, Intent intent) {
    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
    if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
        // Device call state: Ringing. A new call arrived and is ringing or waiting. In the latter case, another call is already active.
        String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
    }else if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK){
        // Device call state: Off-hook. At least one call exists that is dialing, active, or on hold, and no calls are ringing or waiting.
        if(lastState.equals(TelephonyManager.EXTRA_STATE_IDLE){
            // outgoing call                
        } else if(lastState.equals(TelephonyManager.EXTRA_STATE_RINGING){
            // incoming call
        }
    }else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
        // Device call state: No activity.
    }
    lastState = state;
}