当我玩“Soundcloud'或者' Saavn'音乐播放应用程序,我开始自己的应用程序,Saavn或Soundcloud中的音乐仍然在后台播放。需要一种方法来使用代码来阻止它。怎么做 ?
我试过了 -
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
String SERVICECMD = "com.android.music.musicservicecommand";
String CMDNAME = "command";
String CMDSTOP = "stop";
if(mAudioManager.isMusicActive()) {
Intent i = new Intent(SERVICECMD);
i.putExtra(CMDNAME , CMDSTOP );
HomeActivity.this.sendBroadcast(i);
}
但是,如果Android的默认音乐播放器在后台播放而不是Saavn和Soundcloud等第三方应用,则它仅用于停止音乐。
答案 0 :(得分:2)
我在此找到的一个可能的解决方案是使用AudioManager.requestAudioFocus(...)函数
AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
代码示例:
int result = am.requestAudioFocus(focusChangeListener, //Request audio focus for playback
AudioManager.STREAM_MUSIC, //Use the music stream.
AudioManager.AUDIOFOCUS_GAIN); //Request permanent focus.
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// other app had stopped playing song now , so u can do u stuff now .
}
音频焦点依次分配给请求它的每个应用程序。这意味着如果另一个应用程序请求音频焦点,您的将失去它。 通过onAudioFocusChange事件侦听器,当AudioFocus发生更改时,将通知应用程序。此侦听器是requestAudioFocus函数中的第一个参数。
这个监听器应该类似于:
private OnAudioFocusChangeListener focusChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch (focusChange) {
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK):
//Lower the volume while ducking (not sure what ducking means really)
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
//TODO: pause audio
break;
case (AudioManager.AUDIOFOCUS_LOSS) :
//TODO: pause audio
break;
case (AudioManager.AUDIOFOCUS_GAIN):
//TODO: Return the volume to normal and resume if paused.
break;
default: break; //empty on default
}
}
};
答案 1 :(得分:0)
我认为不可能停止其他应用的服务,因为您可能不知道processid,只有在您知道应用的Pid时才能停止应用的服务
<强> android.os.Process.killProcess(processIdKillService)强>