5

I use this code for pausing music player, it pauses default music player but doesn't work on other music players if they are installed. For example poweramp, realplayer etc

Here is code below which I use to pause music:-

AudioManager mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);    

if (mAudioManager.isMusicActive()) 
{
  Intent i = new Intent("com.android.music.musicservicecommand");

  i.putExtra("command", "pause");
  ListenAndSleep.this.sendBroadcast(i);
}
Kamran
  • 53
  • 1
  • 5

2 Answers2

9

Wouldn't it be easier to simply use media buttons? Most, if not all, players should handle those.

private static void sendMediaButton(Context context, int keyCode) {
    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);
}

Then you could use:

sendMediaButton(getApplicationContext(), KeyEvent.KEYCODE_MEDIA_PAUSE);

You could also send a stop key event. Here's a link with the relevant keys, http://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_MEDIA_PAUSE

firemaples
  • 1,521
  • 13
  • 18
MohammadAG
  • 465
  • 1
  • 3
  • 9
  • ThankYou Buddy, It worked well with all most downloaded music player – Kamran Feb 07 '14 at 19:54
  • This answer not working for me. May I know why it's not working? I have checked in Android 8. [this linked answer works for me](https://stackoverflow.com/a/45373093/8892050). – Ranjit Apr 06 '21 at 06:55
0
public static void pauseMusic() {

    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

}

private static void sendKeyEvent(PendingIntent pi, Context context, Intent intent) {
    try {
        pi.send(context, 0, intent);
    } catch (PendingIntent.CanceledException e) {
        Log.e(TAG, "Error sending media key down event:", e);
    }
}
hai046
  • 61
  • 1
  • 7