java - 任何应用程序都可以广播操作名称为 "android.intent.action.MEDIA_BUTTON"的 Intent

标签 java android android-intent

我的应用程序已注册 Intent (“android.intent.action.MEDIA_BUTTON”),以处理使用以下代码按下的有线耳机按键

<receiver
    android:name=".HeadsetEventReceiver"
    android:enabled="true" >
    <intent-filter android:priority="2147483647" >
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

接收器HeadsetEventReceiver在接收此Intent时执行一些操作。

现在我有一个示例应用程序,它使用以下代码广播一个 Intent,其操作为 "android.intent.action.MEDIA_BUTTON" 以及有效的 KeyEvent 对象。

Intent newIntent = new Intent("android.intent.action.MEDIA_BUTTON")  ;
KeyEvent event = new KeyEvent(System.currentTimeMillis(), System.currentTimeMillis(), KeyEvent.ACTION_DOWN, 79, 1, 1, 1, 1, 1, InputDevice.SOURCE_TOUCHPAD);
newIntent.putExtra(Intent.EXTRA_KEY_EVENT, event);
getApplicationContext().sendBroadcast(newIntent);

我的应用程序正在接收此 Intent 并处理此数据,就好像它实际上是由于耳机按键按下而广播的。

我的查询是,当任何应用程序尝试使用 native Intent 发送广播时(例如:“android.intent.action.BOOT_COMPLETED”),会引发 securityException 。为什么它不适用于上述 Intent("android.intent.action.MEDIA_BUTTON")。

最佳答案

4.0 或更高版本起,Android 文档表示您必须使用 registerMediaButtonEventReceiver 来注册 Intent 操作。如果不注册 registerMediaButtonEventReceiver,您将不会收到广播消息。

下面是记录的代码 here

AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
...

// Start listening for button presses
am.registerMediaButtonEventReceiver(RemoteControlReceiver);
...

// Stop listening for button presses
am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);

因此,如果您使用registerMediaButtonEventReceiver,那么您将获得广播,否则您不会。

关于java - 任何应用程序都可以广播操作名称为 "android.intent.action.MEDIA_BUTTON"的 Intent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34176085/

相关文章:

java - 输入已更新到数据库中的错误字段

Android - 使用最后一个操作与 Intent 共享

android - 1 个应用程序处理所有 NFC 请求,还是很多应用程序?

java - Spring Boot Thymeleaf 下拉列表选项不显示值

java - fragment 数组上的 NullPointerException

java - Spinner String 项目值获取(不是字符串名称)android

java - 无法使用 Android 默认视频播放器使用 Intent 播放视频

javascript - Websocket.onmessage 没有触发

java - 无法在jetty 9.4.16.v20190411 : receiving FileNotFoundException for jar that is in the war under WEB-INF/lib中部署WAR

java - Android - 如何在通知面板中添加 [切换按钮]? (你可以切换 Wifi、蓝牙、平面模式等的地方。)