Android 利用AudioManager控制后台音乐播放器暂停,播放

1.

通过触发媒体的按钮来操作播放器状态:KeyEvent.KEYCODE_MEDIA_PAUSE 

public static void sendMediaButton(Context context, int keyCode) {
    AudioManager audioManager= (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    //先判断后台是否再播放音乐
    if (audioManager.isMusicActive()){
        KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
        Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
        context.sendOrderedBroadcast(intent,null);

        keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
        intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
        context.sendOrderedBroadcast(intent,null);
    }
}
 2.通过AudioManager获取音频焦点AudioFocus,来竞争使用audio做停止播放或者降低声音的处理 
AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE); 
am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); 
AudioManager.AUDIOFOCUS_GAIN:永久获取媒体焦点(播放音乐) 估计音乐播放器使用了此方法,在播放视频时调用,不起作用 
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT 暂时获取焦点 适用于短暂的音频 
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK Duck我们应用跟其他应用共用焦点 我们播放的时候其他音频会降低音量

你可能感兴趣的:(Android)