如何使用Android(Java)停止在后台播放所有音乐?

时间:2017-04-18 10:32:51

标签: java android audio android-audiomanager

我坚持使用最后一段代码。 我想在按下按钮时播放闹钟。 闹钟在MUSIC_STREAM上播放,因为它只需通过耳机/耳机播放,所以没有其他人受到干扰。

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);
}

^令人惊讶的是,没有工作。

2 个答案:

答案 0 :(得分:0)

请参阅“获取和释放音频焦点”in the android docs

答案 1 :(得分:0)

使用以下代码:

   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);

    }
相关问题