无法捕捉 android.intent.action.MEDIA_BUTTON

问题描述

我使用 TextToSpeech 阅读一些文本的应用完成了 90%,但在这部分已经卡住了几天。我想要的只是让我的蓝牙耳机(小米的 Mi 运动蓝牙耳机)的播放/暂停按钮播放/暂停 TextToSpeech。我认为这是我需要抓住的 android.intent.action.MEDIA_BUTTON,所以我添加了这些:

在 AndroidManifest.xml 中:

<receiver android:name=".ButtonReceiver">
       <intent-filter
             android:priority="10000">              
             <action android:name="android.intent.action.MEDIA_BUTTON"/>
       </intent-filter>
</receiver>

然后是ButtonReceiver.java类

public class ButtonReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context,Intent intent) {
        
        Toast.makeText(context,"debug media button test",Toast.LENGTH_LONG).show();
        // will finish the code once I catch this intent
    }
}

调试文本不显示。虽然如果我将 <action android:name="android.intent.action.MEDIA_BUTTON"/> 更改为 <action android:name="android.media.VOLUME_CHANGED_ACTION"/>,当我按下耳机的音量增大或减小时它确实会显示文本,但这并不是我想要的。我只希望应用响应播放/暂停按钮。

然后我读到我需要使用 registerMediaButtonEventReceiver,所以我尝试在 MainActivity.java 中添加它:

 private AudioManager audioManager;
 private ComponentName componentName;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        audioManager = (AudioManager) this.getSystemService(AUDIO_SERVICE);
        componentName = new ComponentName(this,ButtonReceiver.class);
        audioManager.registerMediaButtonEventReceiver(componentName);

}

还是不行。此外,它说 registerMediaButtonEventReceiver 已弃用,所以我想知道这是否是它不起作用的原因。

进一步阅读 official document page,它说明了这一点:

如果您运行的是 Android 5.0(API 级别 21)或更高版本,请调用 FLAG_HANDLES_MEDIA_BUTTONS MediaBrowserCompat.ConnectionCallback.onConnected。这会 自动调用您的媒体控制器的 dispatchMediaButtonEvent(), 它将密钥代码转换为媒体会话回调。

我觉得这很愚蠢,因为我不需要这个额外的模块来播放媒体。我所需要的只是检测耳机按钮按下情况。无论如何,我尝试实现 MediaSession 但很快就放弃了,因为它很快结束了太多对我的应用程序无用的代码,因为我的应用程序不是音频播放器应用程序!

有什么建议吗?我该怎么办?

解决方法

我终于自己找到了解决方案!我没有创建单独的 BroadcastReceiver 类,而是在 MainActivity.java 中添加了一个公共静态类:

public static class ButtonReceiver extends BroadcastReceiver {
       
        @Override
        public void onReceive(Context context,Intent intent) {
            String intentAction = intent.getAction();
            Toast.makeText(context,"debug media button test",Toast.LENGTH_SHORT).show();
            ...
        }
}

然后在 onCreate 中添加这一行:

((AudioManager)getSystemService(AUDIO_SERVICE))
.registerMediaButtonEventReceiver(new ComponentName(this,ButtonReceiver.class));

最后在 AndroidManifest.xml 中:

<receiver android:name=".MainActivity$ButtonReceiver"
       android:enabled="true">
       <intent-filter
            android:priority="10000">
            <action android:name="android.intent.action.MEDIA_BUTTON"/>
       </intent-filter>
</receiver>

它有效!该应用现在可以使用此设置捕获 MEDIA_BUTTON 意图!

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...