2014-02-07 185 views
4

我使用此代碼暫停音樂播放器,它會暫停默認的音樂播放器,但如果安裝了其他音樂播放器則不起作用。例如後級時,RealPlayer等如何在android中暫停不同的音樂播放器?

這裏是下面的代碼,我用它來暫停音樂: -

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

回答

8

那豈不是更容易簡單地使用多媒體按鍵?大多數(如果不是全部的話)玩家應該處理這些。

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

那麼你可以使用:

sendMediaButton(getApplicationContext(), KeyEvent.KEYCODE_MEDIA_PAUSE); 

你也可以發送一個停止鍵事件。這裏有一個鏈接的相關密鑰,http://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_MEDIA_PAUSE

+0

ThankYou Buddy,它適用於所有最下載的音樂播放器 – Kamran

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); 
    } 
} 
相關問題