如何使用 Android (Java) 停止所有背景音乐播放?

How to stop all music playing in background with Android (Java)?

我坚持使用最后一段代码。 我想要在按下按钮时播放闹钟。 闹钟通过 MUSIC_STREAM 播放,因为它需要通过 headphones/earpieces 播放,这样就不会打扰其他人。

public void playAlarm(){
try {
        Uri alert =  RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(this, alert);
        final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        originalVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        audioManager.setMode(AudioManager.MODE_IN_CALL);
        audioManager.setSpeakerphoneOn(false);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, alarmVolume, 0);

        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                                 @Override
                                                 public void onCompletion(MediaPlayer mp) {
                                                     audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, originalVolume, 0);
                                                 }
                                             });
    } catch(Exception e) {
    }
}

^ 这段代码在触发警报时运行。奇迹般有效。播放默认警报声音并重复播放。当我关闭该应用程序时,声音停止了 - 就像我想要的那样。

public void killApp(){
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
finish();

    moveTaskToBack(true);
    android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(1);
}

^ 这也行。

不起作用的部分是:

private static void sendMediaButton(Context context, int keyCode) {
    KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
    Intent intentPause = new Intent(Intent.ACTION_MEDIA_BUTTON);
    intentPause.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
    context.sendOrderedBroadcast(intentPause, null);

    keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
    intentPause = new Intent(Intent.ACTION_MEDIA_BUTTON);
    intentPause.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
    context.sendOrderedBroadcast(intentPause, null);
}

^ 它会暂停 PowerAmp 或 Player.fm(以及其他音乐播放器)的音乐,并让我的闹钟播放,但它也会在我的默认音乐应用程序 (PowerAmp) 上重新播放一首歌曲 - 音量非常低,但我的闹钟和歌曲都可以听到。

当我使用 Player.fm 播放音乐时,播放器也会暂停,闹钟会响起,但我的默认音乐应用程序会再次开始播放。

我已经尝试在网络上搜索所有这些代码:

private static void sendMediaButton2(final Context context, int keyCode){
    Intent mediaEvent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY);
    mediaEvent.putExtra(Intent.EXTRA_KEY_EVENT, event);
    context.sendBroadcast(mediaEvent);

    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            Intent mediaEvent = new Intent(Intent.ACTION_MEDIA_BUTTON);
            KeyEvent event = new KeyEvent(KeyEvent.ACTION_UP,KeyEvent.KEYCODE_MEDIA_PLAY);
            mediaEvent.putExtra(Intent.EXTRA_KEY_EVENT, event);
            context.sendBroadcast(mediaEvent);
        }
    }, 100);
}

^ 不工作

public void stopMusicPlaying5(){
    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 );
        MapsActivity.this.sendBroadcast(i);
    }
}

^ 不工作

public void stopMusicPlaying(){
    KeyEvent ke = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE);
    Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);

    // construct a PendingIntent for the media button and unregister it
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    //PendingIntent pi = PendingIntent.getBroadcast(AppContext.getContext(),
    //        0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
    intent.putExtra(Intent.EXTRA_KEY_EVENT, ke);
    //sendKeyEvent(pi, AppContext.getContext(), intent);

    ke = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PAUSE);
    intent.putExtra(Intent.EXTRA_KEY_EVENT, ke);
    //sendKeyEvent(pi, AppContext.getContext(), intent);

    //        android.intent.action.MEDIA_BUTTON

}

^ 不工作

public void stopMusicPlaying1(){
    long eventtime = SystemClock.uptimeMillis();

    Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
    KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT, 0);
    downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent);
    sendOrderedBroadcast(downIntent, null);
}

^ 不工作

public void stopMusicPlaying4(){
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    if (audioManager != null){
        audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
        KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE);
        audioManager.dispatchMediaKeyEvent(event);
    }
}

public void stopMusicPlaying2(){
    long eventtime = SystemClock.uptimeMillis();

    Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
    KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_STOP, 0);
    upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent);
    sendOrderedBroadcast(upIntent, null);
}

^ 而且,令人惊讶的是,不起作用。

见"Acquiring and releasing audio focus"in the android docs

使用以下代码:

   AudioManager.OnAudioFocusChangeListener focusChangeListener =
            new AudioManager.OnAudioFocusChangeListener() {
                public void onAudioFocusChange(int focusChange) {
                    AudioManager am = (AudioManager) 
getSystemService(AUDIO_SERVICE);
                    switch (focusChange) {

                        case 
(AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK):
                            // Lower the volume while ducking.
                            player.setVolume(0.2f, 0.2f);
                            break;
                        case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT):
                            player.pause();
                            break;

                        case (AudioManager.AUDIOFOCUS_LOSS):
                            player.stop();
                            break;

                        case (AudioManager.AUDIOFOCUS_GAIN):

                            player.setVolume(1f, 1f);

                            break;
                        default:
                            break;
                    }
                }
            };

    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);

// Request audio focus for playback
    int result = am.requestAudioFocus(focusChangeListener,
// Use the music stream.
            AudioManager.STREAM_MUSIC,
// Request permanent focus.
            AudioManager.AUDIOFOCUS_GAIN);


    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        player.setSource(video);

    }