我研究了ACTION_MEDIA_BUTTON的意图,我试着用它来拦截按下按钮,然后用祝酒词在屏幕上呈现它们。我注册了接收器来截取两个意图:
ACTION_HEADSET_PLUG -插入headsetACTION_MEDIA_BUTTON -接收按钮按下这是我在主要活动中完成的:
IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
mediaFilter.setPriority(10000);
registerReceiver(_receiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
registerReceiver(_receiver, mediaFilter);这是接收器中处理按钮按下的部分:
if (action.equals(Intent.ACTION_HEADSET_PLUG))
{
Toast.makeText(context, "earphones activity",Toast.LENGTH_SHORT).show();
if (intent.getExtras().getInt("state")==1)//if plugged
Toast.makeText(context, "earphones plugged",Toast.LENGTH_LONG).show();
else Toast.makeText(context, "earphones un-plugged",Toast.LENGTH_LONG).show();
}
else
if (action.equals(Intent.ACTION_MEDIA_BUTTON))
{
Toast.makeText(context, "button pressed",Toast.LENGTH_LONG).show();
key=intent.getExtras().getString("EXTRA_KEY_EVENT");
Toast.makeText(context, key,Toast.LENGTH_LONG).show();
}现在,处理耳机插件和拆卸的部分工作正常,但拦截按钮按下的部分却不是。
处理ACTION_MEDIA_BUTTON的代码有什么不工作的原因吗?
我需要特别许可才能拦截这样的意图吗?
我正在使用三星的Galaxy S2来测试代码。
我看过所有类似的帖子,什么都试过了。不幸的是,似乎什么都起不到作用。
发布于 2012-02-14 10:24:42
我最近开发了一个应用程序,它响应了媒体按钮。我在三星Galaxy上测试了它,它起了作用。
首先,在您的AndroidManifest.xml中,在<application>区域内放置以下内容:
<!-- Broadcast Receivers -->
<receiver android:name="net.work.box.controller.receivers.RemoteControlReceiver" >
<intent-filter android:priority="1000000000000000" >
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>然后,在另一个文件中创建一个BroadcastReceiver:
public class RemoteControlReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction()) {
KeyEvent event = (KeyEvent) intent .getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
if (event.getAction() == KeyEvent.ACTION_DOWN) {
context.sendBroadcast(new Intent(Intents.ACTION_PLAYER_PAUSE));
}
}
}
}这可能是,而不是--最好的解决方案(特别是上面硬编码的android:priority )。然而,它尝试了几种其他的技术,但似乎没有一种有效。所以我得用这个..。希望我能帮上忙。
发布于 2012-02-16 20:36:35
谢谢你的贡献。
对于所有其他在这里挣扎的人来说,最后的结论是:
在经历了大量的热泪之后,我终于意识到我可以拦截两种类型的广播:一些像ACTION_HEADSET_PLUG这样的广播需要注册在活动代码中。
其他如ACTION_MEDIA_BUTTON,则需要在Manifest文件中注册。
在这个例子中,为了拦截这两个意图,我们需要同时执行这两个步骤。
在代码和清单文件中设置它。
发布于 2012-02-14 10:12:30
if (Intent.ACTION_MEDIA_BUTTON.equals(action)) {
if (intent.hasExtra(Intent.EXTRA_KEY_EVENT)) {
String key = intent.getStringExtra(Intent.EXTRA_KEY_EVENT);
toast("Button "+key+" was pressed");
} else
toast("Some button was pressed");
}此代码返回Toast "Button null被按下“
https://stackoverflow.com/questions/9056814
复制相似问题