我在我的应用程序中流式传输音频。已经完成,但是当我接到电话时,我应该暂停流直到通话结束,然后再次播放流。是否可以在android中接听电话时暂停和播放流?
你应该使用 Audio Focus 监听器。不需要电话状态来执行此操作,这确实是一种不好的做法(因为该许可完全侵犯了隐私)。
最好的一点是,当用户开始在另一个应用程序中播放音乐或导航试图说些什么时,您也会收到提醒。
这里有一个关于如何使用它的好文档:
http://developer.android.com/training/managing-audio/audio-focus.html
您可以使用
PhoneStateListener
查看手机状态,并在使用手机时暂停音频流。 android 参考 向您展示了您可以使用的回调,这个示例 向您展示了如何使用它。请注意,您需要向清单添加权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE">
试试这个更简单的代码,我已经测试过了…… (完整代码在这里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
在你的活动中实现这个接口
AudioManager.OnAudioFocusChangeListener
关于覆盖方法
override fun onAudioFocusChange(focusChange: Int) {
if (focusChange <= 0) {
//pause music
mediaPlayer!!.pause()
} else {
//play music
mediaPlayer!!.start()
}
并在您开始播放音频时发送请求
requestAudioFocus(
this,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN
)
这将处理所有消息、电话等。您的音频将暂停并自动启动。