如何在接到电话时暂停并播放音频流

问题描述:

我在我的应用程序中流式传输音频。已完成,但是当我收到一个呼叫时,我应该暂停流,直到呼叫结束,然后再次播放流。在android中接收呼叫时是否可以暂停播放流?如何在接到电话时暂停并播放音频流

+0

http://*.com/questions/5610464/stopping-starting-music-on-incoming-calls – Madi

您可以使用PhoneStateListener看手机的状态,并暂停使用音频流时,手机正在使用中。 android reference显示您可以使用的回调,this example显示如何使用它。请注意,您需要一个允许添加到您的清单:

<uses-permission android:name="android.permission.READ_PHONE_STATE"> 
+0

我试着但不工作。你能举个例子吗 – HARIDASS

+0

你尝试了什么,它以什么方式不起作用?使用代码和详细信息编辑您的问题,以便我们可以帮助您。 – Tobbe

+0

我已经完成了特贝谢谢你的帮助.... – HARIDASS

试试这个简单的代码,我测试过这... (完整的代码是在这里http://blog.kerul.net/2012/01/how-to-pause-audio-while-call-is.html

public class UrClassActivity { 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    private MediaPlayer mp; 
    ... 
    ... 
    ... 
    //this is a code segmentation 
    //THis two lines of codes need to be inserted to the onCreate method 
    //This following codes dealing with the phone-state 
    //detect voice incoming call 
    //onCallStateChanged method will be executed if there's incoming 
    //or outcoming call 
    PhoneStateListener phoneStateListener = new PhoneStateListener() { 
     @Override 
     public void onCallStateChanged(int state, String incomingNumber) { 
      if (state == TelephonyManager.CALL_STATE_RINGING) { 
       //INCOMING call 
       //do all necessary action to pause the audio 
       if(mp!=null){//check mp 
        setPlayerButton(true, false, true); 

        if(mp.isPlaying()){ 

         mp.pause(); 
        } 
       } 

      } else if(state == TelephonyManager.CALL_STATE_IDLE) { 
       //Not IN CALL 
       //do anything if the phone-state is idle 
      } else if(state == TelephonyManager.CALL_STATE_OFFHOOK) { 
       //A call is dialing, active or on hold 
       //do all necessary action to pause the audio 
       //do something here 
       if(mp!=null){//check mp 
        setPlayerButton(true, false, true); 

        if(mp.isPlaying()){ 

         mp.pause(); 
        } 
       } 
      } 
      super.onCallStateChanged(state, incomingNumber); 
     } 
    };//end PhoneStateListener 

    TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); 
    if(mgr != null) { 
     mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); 
    } 
    ... 
    ... 
    ... 

}//end onCreate 

}//end class 
+0

当然在AndroidManifest.xml中放入

你应该使用Audio Focus听众。电话状态不需要这样做,并且是非常糟糕的做法(因为该许可完全是隐私侵入)。

最好的事情是,当用户在另一个应用程序中开始播放音乐或导航试图说点什么时,您也会收到一个提醒。

有关于如何在这里使用它一个很好的文档:

http://developer.android.com/training/managing-audio/audio-focus.html