Android - 启动视频时暂停音乐播放器

时间:2012-07-16 12:12:25

标签: android android-intent android-emulator android-widget

我有和音频播放器和视频播放器的应用程序。我希望当音频播放器在后台播放时我启​​动视频,音频播放器停止播放。

我可以通过在打开视频时发送意图,在广播接收器上轻松实现这一点,并在音频播放器中侦听该意图并在onReceive()中停止它。

但是,我想将此功能不仅扩展到我的音频播放器,还扩展到所有音频播放器。所以我想如果在视频播放器打开时有标准意图发送?

1 个答案:

答案 0 :(得分:0)

您应该使用音频焦点。如果是RandomMusicPlayer示例android项目:

public class AudioFocusHelper {
    AudioManager mAM;
    MusicFocusable mFocusable;

    private final AudioManager.OnAudioFocusChangeListener listener = new AudioManager.OnAudioFocusChangeListener() {

        @Override
        /** 
         * Called by AudioManager on audio focus changes. We implement this by calling our
         * MusicFocusable appropriately to relay the message.
         */
        public void onAudioFocusChange(int focusChange) {
            if (mFocusable == null) return;
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN:
                    mFocusable.onGainedAudioFocus();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS:
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    mFocusable.onLostAudioFocus(false);
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    mFocusable.onLostAudioFocus(true);
                    break;
                 default:
            }
        }
    };;

    public AudioFocusHelper(Context ctx, MusicFocusable focusable) {
        mAM = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
        mFocusable = focusable;
    }

    /** Requests audio focus. Returns whether request was successful or not. */
    public boolean requestFocus() {
        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED ==
            mAM.requestAudioFocus(listener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }

    /** Abandons audio focus. Returns whether request was successful or not. */
    public boolean abandonFocus() {
        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAM.abandonAudioFocus(listener);
    }
}