Playing videos using TextureView in Android

If you want to display an online video or any data stream, such as video or OpenGL scene, you can do it with surfaceview or TextureView in Android.

1) Surfaceview, brother of. TextureView

The video or OpenGL content of an application is often displayed in a special UI control: surfaceview.

Surfaceview works by creating a new window behind the application window. This method is very efficient because there is no need to redraw the application's window when the surfaceview window is refreshed (the view drawing mechanism of Android ordinary windows is layer by layer. Any sub element or local refresh will cause the whole view structure to be redrawn once, so the efficiency is very low, but it is more than enough to meet the needs of ordinary application interfaces). However, surfaceview also has some very inconvenient restrictions.

Because the content of surfaceview is not on the application window, transformations (translation, scaling, rotation, etc.) cannot be used. It is also difficult to put it in listview or Scrollview. Some features of UI controls, such as view. Setalpha (), cannot be used.

2) TextureView in. Android 4.0.

In order to solve the problem we just mentioned above, TextureView is introduced in Android 4.0;

Compared with surfaceview, TextureView does not create a separate surface for painting, which enables it to perform some transformation operations and set transparency like a general view.

In addition, TextureView must be in the window opened by hardware acceleration.

Problems encountered in the project:

1. When playing video with surfaceview before, switching from picture to video will cause black screen.

2. The flexibility of surfaceview is not as good as that of TextureView.

The following is the implementation source code for your reference

Mainactivity.java file

When TextureView is created, the image is displayed. Then initialize the player and preload the video. If the video file does not exist, copy it from assets to sdcard directory. After the video is loaded, the image is hidden. By default, the image on my side displays the image of Android project. You can display the desired image according to your needs.

activity_ Main.xml layout file

Put a TextureView and an ImageView. TextureView initializes and displays the ImageView... Hide the ImageView when the video is playing, and there will be no black screen when switching over.

If there is a problem of flashing screen when playing online video, you need to start a thread to play the video asynchronously, and then use handle to delay to hide the picture. I use a delay of 300 milliseconds

Final effect

Demo source code download

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>