使用Broadcast控制播放器,新方法…

来源:互联网 发布:张龙java培训视频 编辑:程序博客网 时间:2024/06/07 14:39
之前通过Broadcast控制播放器的方法是:
   private void pauseMusic() {
                Intent freshIntent = new Intent();
         freshIntent.setAction("com.android.music.musicservicecommand.pause");
              freshIntent.putExtra("command", "pause");
          sendBroadcast(freshIntent);
      }
经过我测试,无效了。API-18,4.3。
以下是新方法:
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);if(mAudioManager.isMusicActive()) { 
        Intent i = new Intent(SERVICECMD);    i.putExtra(CMDNAME , CMDSTOP ); 
   YourApplicationClass.this.sendBroadcast(i); 
}
以下是命令:
public static final String CMDTOGGLEPAUSE = "togglepause";  
public static final String CMDPAUSE = "pause";  
public static final String CMDPREVIOUS = "previous";  
public static final String CMDNEXT = "next";  
public static final String SERVICECMD = "com.android.music.musicservicecommand";  
public static final String CMDNAME = "command";  
public static final String CMDSTOP = "stop";
===========如果以上还是不行,看下面========================
以下方法适合所有播放器
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_PLAY_PAUSE, 0); 
downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent); 
sendOrderedBroadcast(downIntent, null); 
//这个upIntent要和上面的downIntent 一起使用,才能播放或者暂停,只用downIntent 会不停切换下一曲,必须重启手机。
Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); 
KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, 0); 
upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent); 
sendOrderedBroadcast(upIntent, null); 

// 下一曲,跟上面一样,downIntent upIntent 要同时用,只用down就变成快进。
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); 
Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); 
KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_NEXT, 0); 
upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent); 
sendOrderedBroadcast(upIntent, null); 

//上一曲,只用down就变成快退。
Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); 
KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS, 0); 
downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent); 
sendOrderedBroadcast(downIntent, null);
Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); 
KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PREVIOUS, 0); 
upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent); 
sendOrderedBroadcast(upIntent, null); 
0 0
原创粉丝点击