Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - checking headset button click

How can I checked if play/pause button in my headset is clicked? After that can I implement some method that could change typical action (play/pause) for my own action (shut down etc.) ?

like image 987
PatLas Avatar asked Jul 02 '26 18:07

PatLas


2 Answers

Right now I am using below code headset button click event it's working for me. try this code

// Receiver
public class MediaButtonEventReceiver extends BroadcastReceiver {

    private static final String TAG = "MediaButtonIntentReceiv";
    public MediaButtonIntentReceiver() {
        super();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String intentAction = intent.getAction();
        if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
            return;
        }
        KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        if (event == null) {
            return;
        }

        int action = event.getAction();
        if (action == KeyEvent.ACTION_DOWN) {
            // do something
            Log.e(TAG, "onReceive: " );
            Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
        }


        abortBroadcast();
    }
}
// Write this code in onCreateview in your activity 

IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
filter.setPriority(1000); //this line sets receiver priority
registerReceiver(r, filter);
//  manifest.xml 
 <receiver android:name=".MediaButtonIntentReceiver">
            <intent-filter >
                <action android:name="android.intent.action.MEDIA_BUTTON"/>
            </intent-filter>
 </receiver>
like image 175
Jaydeep Chauhan Avatar answered Jul 04 '26 07:07

Jaydeep Chauhan


If you are trying to listen for this from an activity in the foreground, use onKeyDown() and watch for KEYCODE_MEDIA_PLAY_PAUSE.

Use a BroadcastReceiver for ACTION_MEDIA_BUTTON if you are trying to listen for this event from the background (e.g., a service playing music).

like image 34
CommonsWare Avatar answered Jul 04 '26 07:07

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!