停止&来电时开始播放音乐 [英] Stopping & starting music on incoming calls
问题描述
我已经实现了一个 Activity,它可以从 Android 中的 URL 播放媒体.
I have implemented an activity that plays media from a URL in Android.
为了在来电时添加暂停功能,我创建了一个接收器,在来电时设置一个变量.活动在 onPause()
中读取这个变量,暂停音乐并重置它.当调用完成并恢复活动时,音乐在 onResume()
中恢复.
In order to add pause functionality when a call is incoming I created a receiver that sets a variable when the call is coming. The activity reads this variable in onPause()
, pauses the music and resets it. When the call is done and the activity is resumed, the music is resumed in onResume()
.
只要活动具有焦点,这就可以正常工作.如果我在播放音乐时返回主屏幕,然后调用来了,则不会调用 onPause()
.因此,我不能停下来开始音乐.
This works fine as long the activity has the focus. If I go back to home screen while the music is playing, and then the call comes, onPause()
is not called. Hence, I can't stop and start the music.
是否有人实现了一种媒体播放器,可以正确拦截来电/去电并停止/开始播放音乐?
Has anybody implemented a media player that intercepts incoming/outgoing calls and stops/starts music correctly?
推荐答案
您可以执行以下操作:
首先,您可以使用 PhoneStateListener
监听呼叫状态的变化.您可以在 TelephonyManager 中注册监听器:
First of all, you can listen for changes in the call state using a PhoneStateListener
.
You can register the listener in the TelephonyManager:
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//Incoming call: Pause music
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play music
} 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);
}
记住在不再需要时使用 PhoneStateListener.LISTEN_NONE
取消注册监听器:
Remember to unregister the listener when it's no longer needed using the PhoneStateListener.LISTEN_NONE
:
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
您可以做的另一件事是监听广播android.intent.action.PHONE_STATE
.它将包含额外的 TelephonyManager.EXTRA_STATE
,它将为您提供有关呼叫的信息.在这里查看文档.
Another thing you can do is listening for the broadcast android.intent.action.PHONE_STATE
. It will contain the extra TelephonyManager.EXTRA_STATE
which will give you information about the call. Take a look at the documentation here.
请注意,在这两种情况下,您都需要 android.permission.READ_PHONE_STATE
权限.
Please note that you'll need the android.permission.READ_PHONE_STATE
-permission in both cases.
这篇关于停止&来电时开始播放音乐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!