我希望在收到来电时暂停音乐,并在通话断开时播放音乐。
为此我创建了
<receiver android:name="my receiver class">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
在我的接收器课程中我做了这个
if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
//Pause Music
} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)
|| intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
System.out.println("on phone disconnected");
//Play music
}
有了这个,我可以在接听电话时暂停音乐,但是当电话断开连接时,音乐会在延迟1-5分钟后播放。
请帮帮我
答案 0 :(得分:1)
我建议在你正在处理媒体播放器的类中实现AudioManager.OnAudioFocusChangeListener。
首先请求像这样的AudioFocus
AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
am.registerMediaButtonEventReceiver(RemoteControlReceiver);
// Start playback.
}
然后覆盖onAudioFocusChange方法
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN: Log.d("Audio focus gained"); // when call is ended
//play music
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: Log.d("Audio focus lost transient"); // Means a call is coming
case AudioManager.AUDIOFOCUS_LOSS: Log.d("Audio focus lost"); // When call is received
//pause music
break;
default: Log.d("Focus changed : " + focusChange);
}
}
以下是文档AudioFocus
答案 1 :(得分:1)
希望这会有所帮助
关于活动或片段,请执行以下操作
@Override
public void onStart() {
// Start music
super.onStart();
}
@Override
public void onStop() {
// Stop music
super.onStop();
}