Search code examples
javaandroidaudioandroid-audiomanager

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


I'm stuck with this last piece of code. I want an alarm to play when a button is pressed. The alarm plays over the MUSIC_STREAM, because it needs to be played through headphones/earpieces only so nobody else got disturbed.

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

^ This piece of code runs when the alarm is triggered. Works like a charm. Plays the default alarm sound and repeats. When I kill the app, the sound stops - like I want.

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

^ This works too.

The part which doesn't work is this:

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

^ It pauses music from PowerAmp or Player.fm (and other musicplayers), and let my alarm play, but it also restarts a song on my default music app (PowerAmp) - the volume is very low, but both my alarm and the song is hearable.

When I play music with Player.fm the player also pauses, the alarm plays, but again, my default music app starts playing.

I've tried searches on the web and all these codes:

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

^ Not working

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

^ Not working

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

}

^ Not working

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

^ Not working

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

^ And, surprisingly, not working.


Solution

  • Use following code:

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