MediaSession的简单使用

一:客户端

1:MediaBrowserCompat用来连接服务端,通过服务端的ComponentName即可达到,连接成功以后,即可创建MediaControllerCompat了:

  MediaBrowserCompat mMediaBrowser = new MediaBrowserCompat(mContext, 
  mServiceInfo.componentName, new MediaBrowserCompat.ConnectionCallback() {
            @Override
            public void onConnected() {
                connectToSession(mMediaBrowser.getSessionToken()); 
            }

            @Override
            public void onConnectionSuspended() {
                GwmLog.d(TAG, "onConnectionSuspended");
                connectMediaService();
            }

            @Override
            public void onConnectionFailed() {
                GwmLog.d(TAG, "onConnectionFailed");
                disConnectMediaService();
            }
        }, null);
        mMediaBrowser.connect();
2:创建MediaControllerCompat对象,MediaControllerCompat不仅可以通过注册callback收取服务端下发的指令,还可以向服务端发送指令作用非常大:
private void connectToSession(MediaSessionCompat.Token token) throws RemoteException {
        MediaControllerCompat mMediaController = new MediaControllerCompat(mContext,     
        token);
        mMediaController.registerCallback(mControllerCallback);
    }

向服务端发送指令可以是:

 mMediaController.getTransportControls().sendCustomAction(action, args);
 mMediaController.sendCommand(command, params, receiver);

以上为两种不同的发送指令的方式,当然服务端接收的时候也是通过不同的方法

3:calback可以获取到服务端下发的指令:

 private final MediaControllerCompat.Callback mControllerCallback = new 
 MediaControllerCompat.Callback() {

        @Override
        public void onSessionReady() {
            Log.d(TAG, "onSessionReady");
        }

        @Override
        public void onSessionDestroyed() {
            Log.d(TAG, "onSessionDestroyed: ");
        }

        @Override
        public void onSessionEvent(String event, Bundle extras) {
            sendSessionEvent(event, displayId, extras);
        }

        @Override
        public void onPlaybackStateChanged(PlaybackStateCompat state) {
            notifyPlaybackStateChanged(state, displayId);
        }

        @Override
        public void onMetadataChanged(MediaMetadataCompat metadata) {
            notifyMetaDataChanged(metadata, displayId);
        }

        @Override
        public void onQueueChanged(List<MediaSessionCompat.QueueItem> queue) {
            notifyQueueChanged(queue, bundle, displayId);
        }
    };

二:服务端

1:继承 MediaBrowserServiceCompat

public class MediaBluetoothService extends MediaBrowserServiceCompat

2:创建MediaSession,通过MediaSession获取客户端传过来的指令对应关系如下:

 sendCustomAction→onCustomAction
 sendCommand→onCommand

 @Override
    public void onCreate() {
        super.onCreate(); 
        MediaSessionCompat mMediaSession = new MediaSessionCompat(this, TAG);
        setSessionToken(mMediaSession.getSessionToken());
        mMediaSession.setCallback(mServiceSessionCallback);
        }

 private class CoreServiceSessionCallback extends MediaSessionCompat.Callback {
        @Override
        public void onCustomAction(String action, Bundle extras) {
            mBluetoothPlayer.sendCustomAction(extras);
        }

        @Override
        public void onCommand(String command, Bundle extras, ResultReceiver cb) {
           switch (command) {
                case CommandActionId.CONTROLLER_COMMAND_MEDIA_PLAY:
                    mBluetoothPlayer.play();
                    break;
                case CommandActionId.CONTROLLER_COMMAND_MEDIA_PAUSE:
                    mBluetoothPlayer.pause();
                    break;
                case CommandActionId.CONTROLLER_COMMAND_MEDIA_SKIP_TO_NEXT:
                    mBluetoothPlayer.next();
                    break;
                case CommandActionId.CONTROLLER_COMMAND_MEDIA_SKIP_TO_PREVIOUS:
                    mBluetoothPlayer.prev();
                    break;
                case CommandActionId.CONTROLLER_COMMAND_SYNC_PLAYING_INFO:
                    mBluetoothPlayer.syncPlayingInfo();
                default:
                    break;
            }
        }

        @Override
        public boolean onMediaButtonEvent(@androidx.annotation.NonNull Intent 
        mediaButtonEvent) {
            sendMediaButtonEvent(mediaButtonEvent);
            return true;
        }

        private void sendMediaButtonEvent(Intent mediaButtonEvent) {
            Bundle bundle = new Bundle();
            bundle.putParcelable(BundleKeys.BUNDLE_DATA, mediaButtonEvent);
            mMediaSession.sendSessionEvent(SESSION_EVENT_MEDIA_BUTTON_EVENT, bundle);
        }
    }

3:服务端发送到客户端,直接通过mMediaSession即可操作

mMediaSession.setMetadata(builder.build());
mMediaSession.sendSessionEvent(PLAYER_ACTIVE_EVENT, bundle);
mMediaSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_NONE, 0, 0).setExtras(bundle).build());

感兴趣的小伙伴可以去客户端的回调里去找,肯定是可以对的上的,以上只是我对MediaSession最浅显的认知,不足之处望求指正

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
我可以给你一个Android使用Camera2Demo的示例代码:import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.ImageFormat; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.ImageReader; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.util.Size; import android.util.SparseIntArray; import android.view.Surface; import android.view.TextureView; import android.widget.Toast;@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public class Camera2Demo { private TextureView textureView; private Context context; private Size previewSize; private Handler backgroundHandler; private HandlerThread backgroundThread; private ImageReader imageReader; private CaptureRequest.Builder previewRequestBuilder; private CameraDevice cameraDevice; private CameraCaptureSession captureSession; private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 0); ORIENTATIONS.append(Surface.ROTATION_90, 90); ORIENTATIONS.append(Surface.ROTATION_180, 180); ORIENTATIONS.append(Surface.ROTATION_270, 270); } public Camera2Demo(TextureView textureView, Context context) { this.textureView = textureView; this.context = context; } public void openCamera() { CameraManager cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); try { String cameraID = cameraManager.getCameraIdList()[0]; CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraID); StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); previewSize = map.getOutputSizes(SurfaceTexture.class)[0]; // 权限检查 if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { return; } cameraManager.openCamera(cameraID, stateCallBack, backgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } private CameraDevice.StateCallback stateCallBack = new CameraDevice.StateCallback() { @Override public void onOpened(@NonNull CameraDevice camera) { cameraDevice = camera; startPreview(); } @Override public void onDisconnected(@NonNull CameraDevice camera) { camera.close(); cameraDevice = null; } @Override public void onError(@NonNull CameraDevice camera, int error) { Toast.makeText(context, "摄像头开启失败", Toast.LENGTH_SHORT).show(); } }; private void startPreview() { SurfaceTexture surfaceTexture = textureView.getSurfaceTexture(); surfaceTexture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight()); Surface previewSurface = new Surface(surfaceTexture); try { previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); previewRequestBuilder.addTarget(previewSurface); cameraDevice.createCaptureSession(Arrays.asList(previewSurface, imageReader.getSurface()), new CameraCaptureSession.StateCallback() { @Override public void onConfigured(@NonNull CameraCaptureSession session) { captureSession = session; try { captureSession.setRepeatingRequest(previewRequestBuilder.build(), null, backgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) { } }, backgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值