Tiny trick: Swap SurfaceTexture between TextureViews.

A SurfaceTexture connects a GLProducer with a GLConsumer on Android, it's easy to swap the producer, since you just disconnect the producer on any thread, and it's easy to swap the consumer if you are in control of the thread that originally generated it. So here is the trick to swap out the consumer while preserve the producer connection: 

  1. Save: SurfaceTexture texture = textureView.getSurfaceTexture();
    This saves the texture, make sure onSurfaceDestroyed() returns false. 
  2. Detach: textureView.getParent().removeView(textureView); 
    This will call SurfaceTexture.detachFromGLContext() for you on the right thread.
  3. Attach: newTextureView.setSurfaceTexture(texture);
    This will call SurfaceTexture.attachToGLContext() for you on the right thread.

After this, your producer that is connected to the texture (MediaCodec decoder / encoder, a render thread, etc), will be producing buffers to the textures to be displayed on the new TextureView. Of course, this trick also works for SurfaceView.