Development of multimedia applications is one of the most popular tasks in the modern ecosystem Android. Users are accustomed to consuming content in video format, be it educational materials, entertainment feeds, or advertising integrations. For a developer, the issue of integrating a video player into the application interface becomes a basic skill that must be mastered in the early stages of learning. This process is not as complicated as it might seem at first glance, but it requires an understanding of the component architecture and proper work with resources. Android Studio. This process is not as complicated as it might seem at first glance, but it requires an understanding of the component architecture and proper work with resources.
There are several approaches to implementing video playback, each of which has its own advantages and disadvantages depending on the requirements of the project. The standard component VideoView is great for simple tasks where you need to quickly display a short video without complex controls. However, for professional solutions that require support for various streaming formats, buffering and a custom interface, engineers choose a more powerful library ExoPlayer from Google. The choice of a specific tool directly affects the performance of the application and ease of use.
In this article we will analyze both methods in detail, provide ready-made code examples and explain the intricacies of setting access rights. You'll learn how to properly place video files in a project, how to manage the player's lifecycle, and how to avoid common mistakes related to memory leaks. Regardless of whether you are creating a simple demo application or a complex media combine, the knowledge gained will help you implement the functionality efficiently and effectively.
Preparing the project and adding resources
The first step before writing code is the correct organization of files in the project structure. Android Studio has a strict hierarchy of folders, and violation of the rules for placing resources can lead to compilation errors. Video files that will be played locally (from the deviceโs memory) must be placed in a special directory raw. If such a folder is not in the section res, you need to create it manually by right-clicking on the folder res and selecting New โ Android Resource Directory.
When creating a directory, specify the resource type raw. File names must be strictly lowercase, without spaces or special characters, only Latin letters, numbers and underscores. For example, the file my_video.mp4 will be correct, but My Video.mp4 will cause a build error.
Use MP4 format with the H.264 codec for maximum compatibility with all versions of Android to avoid playback problems on older devices.
If your video is stored in Internet, you do not need to upload it to the project, but you will need to configure network access permission. Open the file AndroidManifest.xml in the project root and add a line with permission INTERNET before the tag application. Without this step, the application simply will not be able to establish a connection with the server to download the data stream, and the player will display a connection error.
โ ๏ธ Attention: Video files in the folder
raware not compressed by the system and increase the size of the installation package (APK). For large videos, it is preferable to use streaming or on-demand downloading.
Implementation through the standard VideoView component
The fastest way to add video to the interface is to use the built-in widget VideoView. This class wraps a standard media resource and provides a basic set of functions: play, pause, rewind, and display controls. To get started, open the layout file activity_main.xml and drag a component from the palette or write it manually in XML code.
In the markup you need to set the width and height parameters. Value match_parent or fixed dimensions in .dp are often used so that the player occupies the desired area of โโthe screen. Don't forget to add the idattribute to be able to access this element from Java or Kotlin code. Below is an example of typical markup for a full screen video player.
<VideoViewandroid:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
After setting up the interface, go to the activity class (for example MainActivity.java). Here you need to find the widget by its ID and set the source of the media file. If the video is in a folder raw, the path is formed using the URI scheme android.resource://. For network video, just pass a string with a URL. Then the method is called start()which initiates playback.
- ๐ Local video: the path is built dynamically through the app context and resource ID.
- ๐ Network video: a stable connection and a correct link to the live stream (not to the site page) are required.
- ๐ฎ Management: by default
VideoViewdoes not show buttons, you need to connectMediaController.
Configuring controller and playback events
Naked VideoView plays video, but does not give the user the opportunity to pause or rewind it. To solve this problem, the class MediaControlleris used. It is a standard control panel with Play/Pause buttons, a progress bar and a timer. To activate it, you need to create a controller instance and bind it to your video player using the setMediaController.
An important aspect is handling the activity lifecycle. Videos should not continue to play if the user minimizes the app or rotates the screen. You need to override the onPause() i onResume() methods in your activity. In the pause method you should call suspend() or stopPlayback(), and when resuming - start(). This saves battery power and system resources.
It is also worth considering playback completion processing. For this, the interface OnCompletionListeneris used. By implementing it, you can app an action that will occur after the video ends: for example, close the activity, start the next video, or show a dialog box thanking you for watching.
Always release video player resources in the onDestroy method to avoid memory leaks and application crashes when the screen orientation is frequently changed.
Advanced level: usage ExoPlayer
For complex projects, standard VideoView is often not enough. The library ExoPlayerdeveloped by Google is the industry standard for media playback on Android. It supports adaptive streaming (DASH, HLS), expanded subtitle formats and a high degree of interface customization. Connecting ExoPlayer requires adding dependencies to the build.gradle module level file.
In the block dependencies you need to add lines with the current versions of the core, ui and common libraries. After synchronizing the project, an instance is created in the code ExoPlayer through the builder. Unlike VideoView, here you control the data source yourself through the MediaItemobject. This gives flexibility in preparing content and preloading subsequent fragments.
ExoPlayer player = new ExoPlayer.Builder(context).build();playerView.setPlayer(player);
MediaItem mediaItem = MediaItem.fromUri(videoUrl);
player.setMediaItem(mediaItem);
player.prepare();
player.play();
The main advantage ExoPlayer is its modularity. You can easily replace the standard controller with your own design, change the buffering logic, or add support for DRM content protection. However, the barrier to entry is higher: more initialization code is required and a deeper understanding of asynchronous processes.
Why is ExoPlayer better for streaming?
ExoPlayer uses adaptive loading logic, automatically switching video quality depending on Internet speed, which prevents constant buffering.
Comparison of methods and choice tool
The choice between VideoView and ExoPlayer depends on the specific tasks of your application. If you just need to show a welcome video at startup or a short instruction, there is no point in complicating the project with a heavy library. A standard widget will handle this in a couple of lines of code and will not increase the size of the APK. The table below provides a detailed comparison of characteristics.
| Characteristics | VideoView | ExoPlayer |
|---|---|---|
| Implementation complexity | Low | Medium/High |
| Support HLS/DASH | Limited | Full |
| UI Customization | Minimal | Full |
| Size applications | Minimal | Increasing |
Developers of enterprise applications or early-stage startups are often advised to start simple. But if you are making an analogue of YouTube or an online cinema service, ExoPlayer this is the only choice. It provides stability on fragmented Android devices and provides tools for playback analytics.
โ ๏ธ Note: ExoPlayer library versions change frequently. Always check Google's official documentation, as initialization syntax may differ in new releases.
Working with access rights and permissions
The security of user data comes first in Google's policy. Starting with certain versions of Android, access to some resources requires explicit confirmation. If your application loads video from external memory (not from a folder raw, but, for example, from an SD card), you may need to request permission READ_EXTERNAL_STORAGE. In modern versions (Android 10 and higher), this is regulated through Scoped Storage.
For network video, as mentioned earlier, the presence of the flag INTERNET in the manifest is critical. If you forget to add it, the application will compile, but when you try to play it, it will crash with an exception SecurityException. Debugging such an error may take time, so check the manifest before starting the emulator.
- ๐ AndroidManifest: always check for tags
<uses-permission>. - ๐ฑ Runtime Permissions: for Android 6.0+, the request for permission to read the file is done programmatically in the activity code.
- โ๏ธ Cloud Storage: when working with Firebase or AWS, make sure that links to files are public or correctly authorized.
โ๏ธ Checklist before starting
Frequently asked questions (FAQ)
Why the video does not play on a real device, but works in emulator?
Most often the problem lies in the codec format. An emulator on a PC can use the computer's system codecs, while a real device has a limited set of supported formats. Make sure the video is encoded in H.264 (video) and AAC (audio) inside an MP4 container.
How to make a video loop (repeat endlessly)?
For VideoView use the method setOnCompletionListenerwithin which call seekTo(0) i start(). In ExoPlayer just set the parameter setRepeatMode(Player.REPEAT_MODE_ALL) before starting.
Is it possible to play YouTube videos directly in the application?
Directly inserting a link to YouTube in VideoView will not work due to content protection. To do this, you need to use the official YouTube Android Player API or open the link through the intent in the native YouTube application.
How to change the video orientation to landscape during playback?
You can programmatically request a change in activity orientation through setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) at the moment playback starts and return to portrait mode after completion.
Where to store large video files so as not to increase the APK size?
The best practice is to store heavy content on a remote server (CDN) and stream it over the network. If you need offline access, implement downloading files to the internal memory of the application upon first launch.