问题
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.) ?
回答1:
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).
回答2:
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>
回答3:
You can use ACTION_MEDIA_BUTTON intent Read more above link Hope this help
来源:https://stackoverflow.com/questions/10125083/android-checking-headset-button-click