Android 关闭后台音频播放

import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;

protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	
		setContentView(R.layout.launcher_activity);
		
		//add by song start
		mAudioManager = (AudioManager)this.getSystemService(AUDIO_SERVICE);
		//mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
		//add by song end
}

@Override
	protected void onResume() {
		super.onResume();
	
		mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);//add by song
		
}


private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
		public void onAudioFocusChange(int focusChange) {
		}
	};



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

public static void sendMediaKeyCode(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)