How to detect bluetooth call/media button press in android app

落花浮王杯 提交于 2019-12-13 07:15:42

问题


I need to detect the bluetooth device button click in my application. i followed many stackoverflow links, but doesn't seem to work for me.

I am using the broadcast receiver as shown below:

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 (KeyEvent.KEYCODE_MEDIA_PLAY == event.getKeyCode()) {    
                //call my method    
            }    
        }    
    }    
}

and my manifest is as follows:

<receiver android:name=".RemoteControlReceiver" >    
   <intent-filter>    
       <action android:name="android.intent.action.MEDIA_BUTTON" />    
       <category android:name="android.intent.category.DEFAULT"/>    
   </intent-filter>    
</receiver>

can any one suggest a way out? Thanks in advance.


回答1:


Is your API level at least 11? The code KEYCODE_MEDIA_PLAY was added in API level 11. The KEYCODE_MEDIA_PLAY_PAUSE code exists since API level 3.

Also, have you tried to configure your intent filter without specifying a category?

Is your RemoteControlReceiver class in the root package of your application? It might have not been able to find ".RemoteControlReceiver".

Other than that, I can't see where you could be doing anything wrong.

I've read in a few posts that you might have to also call registerMediaButtonEventReceiver and unregisterMediaButtonEventReceiver. Have you tried this?

To register:

audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
componentName = new ComponentName(getPackageName(),
    RemoteControlReceiver.class.getName());
audioManager.registerMediaButtonEventReceiver(componentName);

And to unregister:

audioManager.unregisterMediaButtonEventReceiver(componentName);


来源:https://stackoverflow.com/questions/17501433/how-to-detect-bluetooth-call-media-button-press-in-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!