即可,但是最近更新 SDK 之后发现这个 API 已经废弃掉了,推荐使用 MediaSession 来代替。
API21 之前的实现可以参考这篇文章,但是 MediaSession 是在新的 api 中加入的,我们可以使用 android.support.v4.media.session.MediaSessionCompat:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * Creates a new session. * * @param context The context. * @param tag A short name for debugging purposes. * @param mediaButtonEventReceiver The component name for your receiver. * If null, this will attempt to find an appropriate * {@link BroadcastReceiver} that handles * {@link Intent#ACTION_MEDIA_BUTTON} from your manifest. * A receiver is required to support platform versions earlier * than {@link android.os.Build.VERSION_CODES#LOLLIPOP}. * @param mbrIntent The PendingIntent for your receiver component that * handles media button events. This is optional and will be used * on {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} and * later instead of the component name. */ publicMediaSessionCompat(Context context, String tag, ComponentName mediaButtonEventReceiver, PendingIntent mbrIntent) {
ComponentNamembr=newComponentName(getPackageName(), MediaButtonReceiver.class.getName()); mMediaSession = newMediaSessionCompat(this, "mbr", mbr, null); /* set flags to handle media buttons */ mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
/* this is need after Lolipop */ mMediaSession.setCallback(newMediaSessionCompat.Callback() { @Override publicbooleanonMediaButtonEvent(Intent intent) { if (!Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) { returnsuper.onMediaButtonEvent(intent); }