Android錄製或播放語音訊息時關閉其他媒體播放
1.傳送系統廣播:
Intent i = new Intent(“com.android.music.musicservicecommand”);
i.putExtra(“command”, “pause”);
context.sendBroadcast(i);
因為其他的播放器不一定註冊監聽了那個廣播,所以大多數情況是不起作用的。
2.通過觸發媒體的按鈕來操作播放器狀態:
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);
}
}
3. 通過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 我們應用跟其他應用共用焦點 我們播放的時候其他音訊會降低音量
後臺播放音樂時,專案中播放視訊,1方法不起作用,2方法有效 3 暫時獲取焦點時,播放視訊,音樂停止,退出播放介面,音樂自動播放
4.寫一個服務,當第三方播放器開啟時 ,開啟這個服務,音樂暫停;關閉服務,音樂繼續
服務類:
private AudioManager mAm;
private static boolean vIsActive=false;
private MyOnAudioFocusChangeListener mListener;
public class MyOnAudioFocusChangeListener implements OnAudioFocusChangeListener {
@Override
public void onAudioFocusChange(int focusChange) {
// TODO Auto-generated method stub
}
}
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d(TAG, “onStartCommand”);
Toast.makeText(getApplicationContext(), “服務已啟動”, 0).show();
mAm = (AudioManager) getApplicationContext().getSystemService(
Context.AUDIO_SERVICE);
vIsActive=mAm.isMusicActive();
mListener = new MyOnAudioFocusChangeListener();
if(vIsActive)
{
int result = mAm.requestAudioFocus(mListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
{
Log.d(TAG, "requestAudioFocus successfully.");
}
else
{
Log.d(TAG, "requestAudioFocus failed.");
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(vIsActive)
{
mAm.abandonAudioFocus(mListener);
}
Log.d(TAG, "onDestroy");
}
呼叫:開始或結束服務
startService(new Intent(MainActivity.this,StartService.class));
stopService(new Intent(MainActivity.this,StartService.class));