目标是拦截来自耳机的广播以及最终的蓝牙,以响应来自耳机的不同类型的点击以改变媒体播放器.此解决方案适用于ICS之前的所有版本.这是我尝试过的一些代码和事情:
....
private BroadcastReceiver mediaButtonReceiver = new MediaButtonIntentReceiver();
....
public void onCreate() {
...
IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
mediaFilter.setPriority(2147483647); // this is bad...I know
this.registerReceiver(mediaButtonReceiver, mediaFilter);
...
}
public class MediaButtonIntentReceiver extends BroadcastReceiver {
private KeyEvent event;
public MediaButtonIntentReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
try {
int action = event.getAction();
switch(action) {
case KeyEvent.ACTION_UP …Run Code Online (Sandbox Code Playgroud) android media-player android-intent android-4.0-ice-cream-sandwich
我在个人安全应用程序中有一个要求,用户必须通过按下音量增大或音量减小按钮尽快启动应用程序.添加此功能的步骤是什么?
我有新的Android版本的问题,即8.0(奥利奥).我必须注册广播,我使用以下代码执行此操作:
// android.intent.action.MEDIA_BUTTON
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
r = new MediaButtonIntentReceiver();
// this line sets receiver priority
filter.setPriority(999);
registerReceiver(r, filter);
Run Code Online (Sandbox Code Playgroud)
这适用于较旧的Android版本,但在Android 8上这不起作用,因为它必须注册显式广播,但我不知道如何.如何注册显式广播来检测媒体按钮?
这是在Manifest.xml中:
<receiver android:name=".MediaButtonIntentReceiver">
<intent-filter android:priority="999">
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)