Android 视频后台播放, home键后台播放

突然给了个视频开发任务,之前做过的都是不可见后停止播放状态使用surfaceView,基本上就搞定了,突然提出后台继续播放,网上也没找到相关资料,所以就总结一下

第一次使用Mediaplayer +SurfaceView

出现了问题,home后会走SurfaceView 的surfaceDestroyed 生命周期,逻辑控制起来比较麻烦,,声音会出现卡顿一下。
	 private final class SurfaceCallback implements Callback{
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }
        public void surfaceCreated(SurfaceHolder holder) {
           
        }
        public void surfaceDestroyed(SurfaceHolder holder) {
          
        }

第二次通过Service+Window 实现后台播放,在后台时,window大小直接变成0 ,可见时设置window大小,这个有一个问题,就是在viewpager+fragment中使用,页面切换要实现切换效果就比较麻烦。

实现思路就是在service中添加window,window中添加surfaceview,通过MediaPlayer去控制播放。

第三次直接使用Mediaplayer+TextureView 实现 home 时不会走onSurfaceTextureDestroyed ,也不会出现声音卡顿问题,确定使用TextureView开发。(悬浮窗播放)

    TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {

        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
            LogUtil.i(TAG, "onSurfaceTextureAvailable");
            mSurfaceTexture = surfaceTexture;
            play(false);
         /*   if (mMediaPlayer != null) {
                mMediaPlayer.setSurface(new Surface(mSurfaceTexture));
                return;
            }*/

        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
            LogUtil.i(TAG, "onSurfaceTextureDestroyed");
            if (mMediaPlayer != null) {
                mSurfaceTexture = null;
                mMediaPlayer.setSurface(null);
            }
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

        }
    };
实现代码后期贴出来

你可能感兴趣的:(Android,笔)