Nataliya Le Loup
Nataliya Le Loup

Reputation: 125

Android MEDIA_BUTTON event not received when music app is playing

My app should catch tap event on bluetooth headset. It is MEDIA_BUTTONS. I use Broadcast receiver. And normally it works, but when I launch music app in the background then music app steals those events and my onReceive method is never called anymore.

What I do is: 1) I register receiver in the manifest:

<receiver android:name=".PlantronicsReceiver">
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </receiver>

2) I register receiver in activity

mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this, PlantronicsReceiver.class));

Do you have any idea how can I receive media button events even with music apps (google play for example) open?

Thank you!

Upvotes: 2

Views: 2286

Answers (1)

gaurav jain
gaurav jain

Reputation: 3234

Check this link : http://developer.android.com/training/managing-audio/audio-focus.html

First you need to get audio focus, then only you can catch MEDIA_BUTTON events. I had the same problem, and the above worked for me.

Regarding use of the intent actions I mentioned in comments, you can check the following:

IntentFilter musicPauseFilter = new IntentFilter(
                    "android.media.action.CLOSE_AUDIO_EFFECT_CONTROL_SESSION");
IntentFilter musicPlayFilter = new IntentFilter(
                    "android.media.action.OPEN_AUDIO_EFFECT_CONTROL_SESSION");

registerReceiver(musicPlay, musicPlayFilter);
registerReceiver(musicPause, musicPauseFilter);

Then you can simply define these receivers and do whatever is desired inside them:

    // Broadcast Receiver for Music play.
    private BroadcastReceiver musicPlay = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            Log.v("gaurav", "Music play started");
            }
    };

    // Broadcast Receiver for Music pause.
    private BroadcastReceiver musicPause = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            Log.v("gaurav", "Music paused");
            }
    };

Hope it helps you.

Upvotes: 2

Related Questions