我正在尝试获取处理ACTION_MEDIA_BUTTON Intent的keyCodes。我正在研究API> 21,下面是我的代码。每次按下耳机按钮,我都会收到keyCode = KEYCODE_HEADSETHOOK。有人可以告诉我何时会收到KEYCODE_MEDIA_PLAY_PAUSE或KEYCODE_MEDIA_NEXT或任何其他与MEDIA相关的keyCode。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
final MediaSession session = new MediaSession(getApplicationContext(), "TRIGGER");
session.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
session.setActive(true);
PlaybackState state = new PlaybackState.Builder()
.setActions(PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_PAUSE |
PlaybackState.ACTION_PLAY_FROM_MEDIA_ID | PlaybackState.ACTION_PAUSE |
PlaybackState.ACTION_SKIP_TO_NEXT | PlaybackState.ACTION_SKIP_TO_PREVIOUS)
.setState(PlaybackState.STATE_PLAYING, 1, 2, SystemClock.elapsedRealtime())
.build();
session.setPlaybackState(state);
session.setCallback(new MediaSession.Callback() {
@Override
public boolean onMediaButtonEvent(final Intent mediaButtonIntent) {
String intentAction = mediaButtonIntent.getAction();
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction))
{
KeyEvent event = (KeyEvent)mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event != null)
{
int action = event.getAction();
int code = event.getKeyCode();
if (action == KeyEvent.ACTION_DOWN) {
Log.i("TRIGGER", "EVENT RECEIVED");
Log.i("TRIGGER", String.valueOf(event));
Log.i("TRIGGER", String.valueOf(action));
Log.i("TRIGGER", String.valueOf(code));
}
}
}
return super.onMediaButtonEvent(mediaButtonIntent);
}
});
}
清单文件中也提到了Intent过滤器,如下所示。
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
按下耳机按钮时的LogCat详细信息。
09-11 17:39:42.134 15765-15789/com.example.amit.myapplication I/OpenGLRenderer﹕ Initialized EGL, version 1.4
09-11 17:39:42.147 15765-15789/com.example.amit.myapplication D/OpenGLRenderer﹕ Enabling debug mode 0
09-11 17:39:46.843 15765-15765/com.example.amit.myapplication I/TRIGGER﹕ EVENT RECEIVED
09-11 17:39:46.843 15765-15765/com.example.amit.myapplication I/TRIGGER﹕ KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_HEADSETHOOK, scanCode=226, metaState=0, flags=0x8, repeatCount=0, eventTime=217783805, downTime=217783641, deviceId=4, source=0x101 }
09-11 17:39:46.843 15765-15765/com.example.amit.myapplication I/TRIGGER﹕ 0
09-11 17:39:46.843 15765-15765/com.example.amit.myapplication I/TRIGGER﹕ 79