【问题标题】:How to pause different music players in android?如何在android中暂停不同的音乐播放器?
【发布时间】:2014-02-07 16:55:57
【问题描述】:

我使用此代码暂停音乐播放器,它会暂停默认音乐播放器,但如果安装了其他音乐播放器,则无法在其他音乐播放器上运行。例如poweramp、realplayer等

下面是我用来暂停音乐的代码:-

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

【问题讨论】:

    标签: android android-audiomanager android-music-player


    【解决方案1】:

    简单地使用媒体按钮不是更容易吗?大多数(如果不是全部)玩家都应该处理这些问题。

    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

    【讨论】:

    • 谢谢好友,它适用于所有下载次数最多的音乐播放器
    • 这个答案对我不起作用。我可以知道为什么它不起作用吗?我已经签入了 Android 8。this linked answer works for me.
    【解决方案2】:
    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多