在后台聆听硬件媒体按钮

时间:2017-03-29 15:10:49

标签: android button background long-press

即使设备已锁定或应用程序处于后台,我也需要捕获媒体按钮的长按事件。 onKey侦听器不适用于后台应用程序。我有一个使用BroadcastReceiver的工作示例,但它只适用于短按。我正在使用AudioManager注册接收器。当我长按按钮时,我在控制台中可以看到的是:

I / MediaSessionService(684):基于语音的互动:即将使用ACTION_WEB_SEARCH

I / ActivityManager(684):从显示0上的uid 1000开始u0 {act = android.speech.action.WEB_SEARCH flg = 0x10800000}

所以我试过通过context.registerReceiver()方法听ACTION_WEB_SEARCH没有成功。我还将带有intent-filter的接收器添加到清单文件中。

我还有其他办法吗?或者有人知道有效的解决方案吗?我一直在搜索和测试这一功能5天,我真的很生气。 = d

1 个答案:

答案 0 :(得分:2)

我找到了你在这里描述的完全相同问题的答案。

您需要做的就是通过长按媒体按钮为要启动的活动添加intent-filter。

屏幕解锁时会调用WEB_SEARCH。

屏幕锁定时会调用VOICE_SEARCH_HANDS_FREE。

为MainActivity添加了操作的清单文件:

<activity
        android:name=".MainActivity"
        android:launchMode="singleTop"
        android:screenOrientation="portrait">
        <intent-filter android:priority="1000000">
            <action android:name="android.speech.action.VOICE_SEARCH_HANDS_FREE" />
            <action android:name="android.speech.action.WEB_SEARCH" />
            <category android:name="android.intent.category.DEFAULT" />

            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>

首次启动应用程序并长按按钮时,屏幕底部会出现一个小对话框。该对话框询问您是否要使用Google应用或您自己的应用完成操作,他们都会听取相同的操作。

不要忘记在你的活动中添加它,否则它将不会显示在你的锁屏上。

@Override
public void onAttachedToWindow() {
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
}