1.
Operate the player state by triggering the media button: 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. Obtain the audio focus AudioFocus through AudioManager to compete to use audio to stop playing or lower the sound.
AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT) ;
AudioManager.AUDIOFOCUS_GAIN: Acquire media focus permanently (play music). It is estimated that the music player uses this method. It is called during video playback and does not work.
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT Temporarily obtains focus is suitable for short-lived audio
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK Duck our application and others When the application shares the focus, other audio will lower the volume when we play