我使用 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
推荐使用,所以我想知道这是否是它不起作用的原因。
从官方文档页面进一步阅读,它告诉我们:
如果您运行的是 Android 5.0(API 级别 21)或更高版本,请调用 FLAG_HANDLES_MEDIA_BUTTONS MediaBrowserCompat.ConnectionCallback.onConnected。这将自动调用您的媒体控制器的 dispatchMediaButtonEvent(),它将键代码转换为媒体会话回调。
我觉得这很愚蠢,因为我不需要这个额外的模块来播放媒体。我只需要检测耳机按钮按下。无论如何,我尝试实现 MediaSession 但很快就放弃了,因为我的应用程序不是音频播放器应用程序,所以很快就结束了太多对我的应用程序无用的代码!
有什么建议吗?我应该怎么办?