TextureView算是一个比较好用的视频控件,能拖拽和放大缩小。不过对它的生命周期都没什么研究一直以为和SurfaceView差不多,可是最近在其他手机上测试的时候发现并不是这样的,用TextureView必须要使用SurfaceTextureListener
textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
});
先说onSurfaceTextureAvailable,在有些手机中可以用textureView.getSurfaceTexture() == null来判断TextureView是否准备完成,而有些手机不行,因为有些手机返回的不是null,可是依然不能使用,在用exoplayer进行测试时
player.setVideoSurface(new Surface(textureView.getSurfaceTexture()));虽然不报错,可画面变成全屏,不再是我设置的自适应,可在onSurfaceTextureAvailable之后使用setVideoSurface()画面就自适应,为什么不自适应,看过exoplayer的DummySurface类就知道exoplayer自己创建了个Surface,所以我的opengl操作都失效了
再来说onSurfaceTextureDestroyed,这也是个坑,在有些手机上隐藏当前activity时,会回调onSurfaceTextureDestroyed,而有些手机不会回调onSurfaceTextureDestroyed,这样就导致一个问题,在有些手机上Surface会被销毁,而有些手机不会销毁,销毁Surface后textureView.getSurfaceTexture()就会变成null,这样就可以通过SurfaceTextureListener和textureView.getSurfaceTexture()来一起判断什么时候player.setVideoSurface(new Surface(textureView.getSurfaceTexture()))了