Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause different music players in android?

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);
}
like image 890
Kamran Avatar asked Feb 14 '23 20:02

Kamran


1 Answers

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

like image 131
MohammadAG Avatar answered Mar 03 '23 13:03

MohammadAG