问题
Can anyone tell me why this is not working on Kitkat anymore and how to solve it?
private Intent player;
player = new Intent(Intent.ACTION_MEDIA_BUTTON);
synchronized (this) {
player.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY));
sendOrderedBroadcast(player, null);
player.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY));
sendOrderedBroadcast(player, null);
}
回答1:
There is new method AudioManager.dispatchMediaKeyEvent(KeyEvent) in API level 19 that was created specifically for this purpose.
http://developer.android.com/reference/android/media/AudioManager.html#dispatchMediaKeyEvent(android.view.KeyEvent)
This code works on KitKat:
AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
long eventtime = SystemClock.uptimeMillis() - 1;
KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, 0);
am.dispatchMediaKeyEvent(downEvent);
eventtime++;
KeyEvent upEvent = new KeyEvent(eventtime,eventtime,KeyEvent.ACTION_UP,KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, 0);
am.dispatchMediaKeyEvent(upEvent);
回答2:
I have no idea why you think that code would be reliable in the first place. There is no requirement that any app do anything in response to those particular pair of broadcasts.
Beyond that, Android is continuing to crack down on apps that send fake system broadcasts like these, such as Android 4.4 blocking apps sending ACTION_MEDIA_MOUNTED broadcasts. I would check LogCat and see if you have any warnings or anything regarding your misuse of this broadcast.
来源:https://stackoverflow.com/questions/19890643/android-4-4-play-default-music-player