2012-12-10 88 views
1

該應用程序偵聽來電,然後停止播放音樂。然後,我希望音樂在通話結束後重新開始。但我在CALL_STATE_IDLE上遇到問題,因爲它在應用程序啓動時檢測到,所以在其方法內的任何調用都將在應用程序啓動時調用。如何防止應用程序啓動時檢測到CALL_STATE_IDLE?

我的代碼如下所示:

@Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    ... 
    listenForIncomingCall(); 
    ... 
    } 
    private void listenForIncomingCall() { 
    PhoneStateListener phoneStateListener = new PhoneStateListener() { 
     @Override 
     public void onCallStateChanged(int state, String incomingNumber) { 
      if (state == TelephonyManager.CALL_STATE_RINGING) { 
       //Incoming call: Pause music 
       //stop playing music 
      } else if (state == TelephonyManager.CALL_STATE_IDLE) { 
       //Not in call: Play music 

      //a code placed here activates on app starts 

      } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) { 
       //A call is dialing, active or on hold 
      } 
      super.onCallStateChanged(state, incomingNumber); 
     } 
    }; 
    TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); 
    if (mgr != null) 

    { 
     mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); 
    } 
} 

我如何避免這種情況?如果不在onCreate中,我如何註冊一些聽衆?

+1

如果您的應用尚未暫停播放,請忽略CALL_STATE_IDLE。 – Michael

+0

@Michael像在我貼的代碼中,或者有更好的方法? – sandalone

回答

2

我找到了一個支持解決方案。隨意使用它。如果有人有更好的,可以隨時與社區分享。

private void listenForIncomingCall() { 
    PhoneStateListener phoneStateListener = new PhoneStateListener() { 
     boolean toTrack = false; //to prevent triggering in onCreate 

     @Override 
     public void onCallStateChanged(int state, String incomingNumber) { 
      if (state == TelephonyManager.CALL_STATE_RINGING) { 
       //Incoming call: Pause music 
       doSomething(); 
      } else if (state == TelephonyManager.CALL_STATE_IDLE) { 
       //Not in call: Play music 
       if (toTrack) { 
        doSomething(); 
       } 
       toTrack = true; 
      } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) { 
       //A call is dialing, active or on hold 
       if (toTrack) { 
        doSomething(); 
       } 
       toTrack = true; 
      } 
      super.onCallStateChanged(state, incomingNumber); 
     } 
    }; 
    TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); 
    if (mgr != null) 

    { 
     mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); 
    } 
} 
+0

很好的答案非常感謝。 –

+0

doSomething();它可以用'pause()'或'start();'方法替換它。如果我在'CALL_STATE_OFFHOOK'中調用'pause()',並在'CALL_STATE_IDLE'中調用'start();',則調用完成後會出現同樣的問題 –

相關問題