1
votes

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.) ?

3

3 Answers

3
votes

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).

5
votes

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>
0
votes

You can use ACTION_MEDIA_BUTTON intent Read more above link Hope this help