0

我想知道长按媒体按钮时如何启动活动。在这种情况下,我不想启动默认活动:媒体阅读器,当媒体按钮被短按时,这个必须继续启动。

希望,我已经明确了。

附属问题:为什么有些硬键,比如搜索按钮,可以直接启动在 manifest.xml 的活动属性中指定它的活动,而其他的,比如媒体按钮,只提到广播动作?

4

1 回答 1

7

我认为你需要做的是:

  1. 将此添加到您的清单中:

    <receiver android:name="com.example.MediaButtonReceiver">
       <intent-filter android:priority="1000000000">
        <action android:name="android.intent.action.MEDIA_BUTTON" />
       </intent-filter>
        </receiver>
    
  2. 创建类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();
                    }
                }
            }
        }
    }
    

我主要是从这里复制的:https ://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaButtonIntentReceiver.java

此外,这取决于MEDIA_BUTTON正在订购的广播,我认为它是。优先级应设置为高于媒体应用程序。不幸的是,媒体应用程序使用默认优先级,并且文档没有说明那是什么(惊喜)。

于 2011-03-28T15:52:37.650 回答