Android 多媒体按键监听相关

import androidx.media.session.MediaButtonReceiver

public class CustomMediaButtonReceiver extends MediaButtonReceiver {
    private static final String TAG = CustomMediaButtonReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        if (context == null) return;
        if (intent == null) return;
        if (intent.getAction() == null) return;


       
        if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
            // 获得KeyEvent对象
            KeyEvent keyEvent = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
            if (keyEvent == null) return;

            // 获得按键字节码
            int keyCode = keyEvent.getKeyCode();
            // 按下 / 松开 按钮
            int keyAction = keyEvent.getAction();
            // 获得事件的时间
            long downtime = keyEvent.getEventTime();

            // 输出点击的按键码

            FucUtil.logMediaKey(context,intent,TAG);

            //注意 有 2次, ACTION_UP 和 ACTION_DOWN
            if (keyAction == KeyEvent.ACTION_UP) return;

            // 说明:当我们按下MEDIA_BUTTON中间按钮时,实际出发的是 KEYCODE_HEADSETHOOK 而不是
            // KEYCODE_MEDIA_PLAY_PAUSE
            if (KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE == keyCode) {
                L.d(TAG,"CustomMediaButtonReceiver PlayerService 1 startOrPause");
                PlayerService.startOrPause(context);
            }
            if (KeyEvent.KEYCODE_HEADSETHOOK == keyCode) {
                L.d(TAG,"CustomMediaButtonReceiver PlayerService 2 startOrPause");
                PlayerService.startOrPause(context);
            }

            if (KeyEvent.KEYCODE_MEDIA_NEXT == keyCode) {
                PlayerService.nextPlay(context);
            }

            if (KeyEvent.KEYCODE_MEDIA_PREVIOUS == keyCode) {
                PlayerService.prePlay(context);
            }
            if (KeyEvent.KEYCODE_MEDIA_STOP == keyCode) {
                PlayerService.stopPlay(context);
            }
        }
    }

}
    private MediaSession mSession = null;

    private ComponentName mbCN;
    private CustomMediaButtonReceiver wireControlReceiver;

    /**
     * 媒体按键监听,线控 相关变量初始化
     */
    private void initMediaBtnReceiverConst(){
        if (mbCN == null)
            mbCN = new ComponentName(getPackageName(), CustomMediaButtonReceiver.class.getName());
        if (wireControlReceiver == null)
            wireControlReceiver = new CustomMediaButtonReceiver();

    }
/**
     * 媒体按键监听,线控
     */
    public void registerMediaBtnReceiver(){
        Context mContext = getApplicationContext();
        initMediaBtnReceiverConst();
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            if (mSession == null)
                mSession = new MediaSession(mContext, "MusicService");
            mSession.setCallback(new MediaSession.Callback() {
                @Override
                public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
//                    FucUtil.logMediaKey(mContext,mediaButtonIntent,"registerMediaBtnReceiver() ");
                    wireControlReceiver.onReceive(mContext, mediaButtonIntent);
                    return super.onMediaButtonEvent(mediaButtonIntent);
                }
            });
            mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS
                    | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
            Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
            ComponentName mediaButtonReceiverComponent = new ComponentName(mContext, WireControlReceiver.class);
            mediaButtonIntent.setComponent(mediaButtonReceiverComponent);
            PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(mContext.getApplicationContext(), 0,
                    mediaButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
            mSession.setMediaButtonReceiver(mediaPendingIntent);
            AudioAttributes.Builder audioAttributesBuilder = new AudioAttributes.Builder();
            audioAttributesBuilder.setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC);
            mSession.setPlaybackToLocal(audioAttributesBuilder.build());
            mSession.setActive(true);
            PlaybackState state = new PlaybackState.Builder()
                    .setActions(
                            PlaybackState.ACTION_PLAY
                                    | PlaybackState.ACTION_PLAY_PAUSE
                                    | PlaybackState.ACTION_PLAY_FROM_MEDIA_ID
                                    | PlaybackState.ACTION_PAUSE
                                    | PlaybackState.ACTION_SKIP_TO_NEXT
                                    | PlaybackState.ACTION_SKIP_TO_PREVIOUS)
                    .setState(PlaybackState.STATE_PLAYING, 0, 1,
                            SystemClock.elapsedRealtime()).build();
            mSession.setPlaybackState(state);

        }

////获得AudioManager对象
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.registerMediaButtonEventReceiver(mbCN);

        Intent mediaButtonIntent = new Intent(
                Intent.ACTION_MEDIA_BUTTON);
        mediaButtonIntent.setComponent(mbCN);
        PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(
                mContext, 0, mediaButtonIntent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

// create and register the remote control client
        RemoteControlClient mRemoteControlClient = new RemoteControlClient(
                mediaPendingIntent);
        audioManager.registerRemoteControlClient(mRemoteControlClient);
        int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
                | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
                | RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                | RemoteControlClient.FLAG_KEY_MEDIA_RATING;
        mRemoteControlClient
                .setTransportControlFlags(flags);
        IntentFilter inFilter = new IntentFilter(
                "android.intent.action.MEDIA_BUTTON");
        inFilter.setPriority(10000);
        mContext.registerReceiver(wireControlReceiver, inFilter);

    }
public class CustomMediaButtonReceiver extends BroadcastReceiver {
    private static final String TAG = CustomMediaButtonReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null) return;
        if (intent.getAction() == null) return;


        if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
            // 获得KeyEvent对象
            KeyEvent keyEvent = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);

            L.d(TAG,   "  KeyEvent----->" + keyEvent.toString());
            if (keyEvent == null) return;

            // 获得按键字节码
            int keyCode = keyEvent.getKeyCode();
            // 按下 / 松开 按钮
            int keyAction = keyEvent.getAction();
            // 获得事件的时间
            long downtime = keyEvent.getEventTime();

            // 输出点击的按键码

            FucUtil.logMediaKey(context,intent,TAG);

            //注意 有 2次, ACTION_UP 和 ACTION_DOWN
            if (keyAction == KeyEvent.ACTION_UP) return;

            // 说明:当我们按下MEDIA_BUTTON中间按钮时,实际出发的是 KEYCODE_HEADSETHOOK 而不是
            // KEYCODE_MEDIA_PLAY_PAUSE
            if (KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE == keyCode) {
                PlayerService.startOrPause(context);
            }
            if (KeyEvent.KEYCODE_HEADSETHOOK == keyCode) {
                PlayerService.startOrPause(context);
            }

            if (KeyEvent.KEYCODE_MEDIA_NEXT == keyCode) {
                PlayerService.nextPlay(context);
            }

            if (KeyEvent.KEYCODE_MEDIA_PREVIOUS == keyCode) {
                PlayerService.prePlay(context);
            }
            if (KeyEvent.KEYCODE_MEDIA_STOP == keyCode) {
                PlayerService.stopPlay(context);
            }
        }
    }
}

你可能感兴趣的:(Android 多媒体按键监听相关)