我的应用程序已注册 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/