Swapnil Swapnil - 1 month ago 25
Android Question

How to know onSurfaceTextureAvailable is called for which TextureView

I am writing an application where I need to display two

TextureView
(s) on my activity. I am attaching videos to each of the
TextureView
instance using
MediaPlayer
objects using the following code inside
onSurfaceTextureAvailable()
:

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

Surface surface = new Surface(surfaceTexture);

mMediaPlayer1 = new MediaPlayer();

try {
mMediaPlayer1.setDataSource(<filePath>);
} catch (IOException e) {
Log.e(TAG, "Unable to load the file from the file system", e);
return;
}

mMediaPlayer1.setSurface(surface);
mMediaPlayer1.setLooping(true);
mMediaPlayer1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
isPlaybackReady = true;
}
});

mMediaPlayer1.prepareAsync();
}


Now, if I have two instances of
TextureView
, how would I know the callback into
onSurfaceTextureAvailable(...)
is for which
TextureView
.

The other way is to setup the
MediaPlayer
objects outside the
onSurfaceTextureAvailable(...)
, by getting a hold over the associated
SurfaceTexture
by calling
TextureView.getSurfaceTexture()
. I tried that as well but it always returns
null
. Is there something else that I need to do for this?

Answer

You can just set two instances of TextureView with different listener.

textureView1.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
        doSomething(textureView1, surfaceTexture, i, i1);
    }
    // implement other methods 


    });

textureView2.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
        doSomething(textureView2, surfaceTexture, i, i1);
    }

    // implement other methods 
    });

}