问题
I would want to know how to launch an activity when long pressing media button. In this case, I don't want to launch the default activity : the media reader, this one must keep lauching when media button has been short pressed.
Hope, I've been explicite.
A.L.
Subsidiary question : Why some hard key, like the search button, can directly launch activity specifying it in the activity attribute of the manifest.xml , and others, like media button, are only mentioned for broadcast action ?
回答1:
I think what you need to do is this:
Add this to your manifest:
<receiver android:name="com.example.MediaButtonReceiver"> <intent-filter android:priority="1000000000"> <action android:name="android.intent.action.MEDIA_BUTTON" /> </intent-filter> </receiver>
Create the class
MediaButtonReceiver
:public class MediaButtonReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { String intentAction = intent.getAction(); if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) { KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); if (event == null) { return; } int keycode = event.getKeyCode(); int action = event.getAction(); long eventtime = event.getEventTime(); if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keycode == KeyEvent.KEYCODE_HEADSETHOOK) { if (action == KeyEvent.ACTION_DOWN) { // Start your app here! // ... if (isOrderedBroadcast()) { abortBroadcast(); } } } } }
I mostly copied this from here: https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaButtonIntentReceiver.java
Also, this depends on the MEDIA_BUTTON
broadcast being ordered, which I assume it is. The priority should be set to something higher than the media app. Unfortunately the media app uses the default priority, and the documentation doesn't say what that is (quelle surprise).
来源:https://stackoverflow.com/questions/3369554/how-to-handle-long-press-media-button-in-order-to-launch-activity