Android Record and Upload Video to Server Using Retrofit 2

In this tutorial, we are going to learn how to record and upload video to server using Retrofit 2. Retrofit 2 is an android third party library that you can add in your android project to simplify network calls. If you are not heard about Android Retrofit before I will suggestion you go over to their website and read more about Retrofit.

If you are interested in uploading an image file to the server using Retrofit, don’t worry. I wrote a tutorial on this topic (Android Image Upload to Server using Retrofit 2) so you can have a look at it to get going with uploading image files in your android project.

In this example, we are going to add a button widget and VideoView in the main layout file of our application. The button widget will be wire with click event. When the button is clicked, it will use Intent action to trigger android device video recording. After the recording, it will upload the video file to the server.

The network call will be handled by Retrofit library and we will create a php script in our server that will move the video file to the folder we wish to stored it.

If everything did not make sense to you, it will by the time we get to the end of this android tutorial.

Recording video and uploading it to a remote server is major part of many android applications. With that in mind, this tutorial will help you achieve that in a few minutes if you are already familiar with android development.

In other to get a visual understanding of what we are going to create in this android tutorial, I have add below some screen shots from the application.


android videoview


Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 24

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidVideoRecording

Package: com.inducesmile.androidvideorecording

Select Empty Activity

Name your activity: SplashActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

Add Library Dependencies in Build.gradle

Lets open the module build.gradle file, we are going to add some third party libraries in our project. Using good third party library can increase productivity and save development time. It helps to prevent reinventing the wheels.

Since we are working with Retrofit 2, we are going the add Retrofit 2 dependency and other dependencies that the library depends on.

Easy permission library is also added. This library makes it easier to implement android run-time permissions in devices that run on Android 6 and above.

Open this file and add the dependencies below.

apply plugin: ''
apply plugin: ''
android {
    compileSdkVersion 25
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.inducesmile.androidvideorecording"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner ""
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), ''
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('', {
        exclude group: '', module: 'support-annotations'
    compile ''
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    compile 'com.squareup.okio:okio:1.7.0'
    compile ''
    compile 'com.squareup.retrofit2:converter-gson:2.0.1'
    compile 'pub.devrel:easypermissions:0.2.0'
    testCompile 'junit:junit:4.12'


We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

    <string name="app_name">Record Video and Upload to Server</string>
    <string name="upload_video">UPLOAD VIDEO</string>
    <string name="read_file">This app needs access to your file storage so that it can read video.</string>


Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorBlack">#000000</color>
    <color name="colorWhite">#ffffff</color>


Since we are going to make network calls in this application that is upload image file over the internet, we will add Internet permission in AndroidManifest.xml. Since we are going to read and write to android external storage, we will add user permission for read and write for android external storage.

Since the device camera will be used for the video recording we will also add uses-feature required. This will enable our application to be available to android device with camera.

Open the AndroidManifest.xml and add the code below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-feature android:name="" android:required="true" />
        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />


As mentioned above, the main layout file will contain a Button and VideoView widgets. This layout file has been created for us when android studio setup our project for us.

Open the activity_main.xml and add the code below

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
        android:layout_alignParentStart="true" />

Right click on your project package folder and select create a new Java interface class. Name the file

Retrofit 2 uses an Interface class to build API end-point bridge with the remote server. This interface class uses annotation to specify the way network calls are constructed. Retrofit also supports most http protocols and Methods.

Inside the Interface class, we will define a method. Name the method uploadFile. Since we are working with files, it is important to add the Multipart annotation.

Open the interface class and add the code below.

import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface VideoInterface {
    Call<ResultObject> uploadVideoToServer(@Part MultipartBody.Part video);

Create a new java class file and name it or anything you wish. This entity class will be used to map the server response object if the upload is successful or not.

Open this file and add the code below to it.

public class ResultObject {
    private String success;
    public ResultObject(String success) {
        this.success = success;
    public String getSuccess() {
        return success;

In the MainActivity class, the instance of the layout button widget is object by calling Activity class method findViewById();

Event click is attached to the button object. Inside the onClick() method of the click event class, we will add an Intent with an action (MediaStore.ACTION_VIDEO_CAPTURE) that will open the device video recording.

Once the video recording ends, the onActivityResult(int requestCode, int resultCode, Intent data)  method is called and it will return the user to the app.

Inside this method, the path to the recorded video is obtained but to read the device external storage, we need to check for run-time permission for storage read and write access.

we will display the recorded video in the VideoView using the setVideoUri() method. To start playing the video, the start() method of the VideoView class is called on its instance.

If the user grant access to the application, the instance of the Retrofit 3 class is created with the baseUrl() and addConvertFactory()methods of Retrofit builder class.

A class is generated from the Interface class by calling the Retrofit object create method. The created class will call the method that was define in the Interface class.

You can use either synchronous or asynchronous call with Retrofit 2. We will use the async call with the enqueue() method.

Open the MainActivity class and add the code below.

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;
import java.util.List;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int REQUEST_VIDEO_CAPTURE = 300;
    private static final int READ_REQUEST_CODE = 200;
    private Uri uri;
    private String pathToStoredVideo;
    private VideoView displayRecordedVideo;
    private static final String SERVER_PATH = "";
    protected void onCreate(Bundle savedInstanceState) {
        displayRecordedVideo = (VideoView)findViewById(;
        Button captureVideoButton = (Button)findViewById(;
        captureVideoButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent videoCaptureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                if(videoCaptureIntent.resolveActivity(getPackageManager()) != null){
                    startActivityForResult(videoCaptureIntent, REQUEST_VIDEO_CAPTURE);
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == Activity.RESULT_OK && requestCode == REQUEST_VIDEO_CAPTURE){
            uri = data.getData();
            if(EasyPermissions.hasPermissions(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)){
                pathToStoredVideo = getRealPathFromURIPath(uri, MainActivity.this);
                Log.d(TAG, "Recorded Video Path " + pathToStoredVideo);
                //Store the video to your server
                EasyPermissions.requestPermissions(MainActivity.this, getString(R.string.read_file), READ_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE);
    private String getFileDestinationPath(){
        String generatedFilename = String.valueOf(System.currentTimeMillis());
        String filePathEnvironment = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        File directoryFolder = new File(filePathEnvironment + "/video/");
        Log.d(TAG, "Full path " + filePathEnvironment + "/video/" + generatedFilename + ".mp4");
        return filePathEnvironment + "/video/" + generatedFilename + ".mp4";
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, MainActivity.this);
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if(uri != null){
            if(EasyPermissions.hasPermissions(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)){
                pathToStoredVideo = getRealPathFromURIPath(uri, MainActivity.this);
                Log.d(TAG, "Recorded Video Path " + pathToStoredVideo);
                //Store the video to your server
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Log.d(TAG, "User has denied requested permission");
    private void uploadVideoToServer(String pathToVideoFile){
        File videoFile = new File(pathToVideoFile);
        RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
        MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);
        Retrofit retrofit = new Retrofit.Builder()
        VideoInterface vInterface = retrofit.create(VideoInterface.class);
        Call<ResultObject>  serverCom = vInterface.uploadVideoToServer(vFile);
        serverCom.enqueue(new Callback<ResultObject>() {
            public void onResponse(Call<ResultObject> call, Response<ResultObject> response) {
                ResultObject result = response.body();
                    Toast.makeText(MainActivity.this, "Result " + result.getSuccess(), Toast.LENGTH_LONG).show();
                    Log.d(TAG, "Result " + result.getSuccess());
            public void onFailure(Call<ResultObject> call, Throwable t) {
                Log.d(TAG, "Error message " + t.getMessage());
    private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
        Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) {
            return contentURI.getPath();
        } else {
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            return cursor.getString(idx);


Now that we have finish with the android client application, we will go ahead to create a php script that will live in the root directory of our web app in the remote server.

Create a php file and name it index.php. Add the code below to the file.


$result = array("success" => $_FILES["video"]["name"]);
$file_path = basename( $_FILES['video']['name']);
if(move_uploaded_file($_FILES['video']['tmp_name'], $file_path)) {
    $result = array("success" => "File successfully uploaded");
} else{
    $result = array("success" => "error uploading file");
echo json_encode($result, JSON_PRETTY_PRINT);


This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email address to be among the first to receive my new android blog post once it is published.


    • Henry
    • Henry
    • Henry
    • Henry
    • Henry

Add a Comment