Features

Developers

How to easily upload videos on your Android app with an Android Service?

October 6, 2022 - Thibault Beyou in Video upload, Android, Kotlin

This article is about how to easily add an upload mechanism from api.video to your Android application with a specific component from the Android API client and the Android video uploader called the UploadService.

In your Android application, if you use the upload API with the Android API client or the Android video uploader, you might have noticed that it is not a piece of cake. Here are the main reasons why:

  • NetworkOnMainThreadException: on the modern Android version, you must not perform network calls on the main thread; otherwise your application will crash with an android.os.NetworkOnMainThreadException . As upload is a synchronous API, you must call it from a Thread.
  • Background: performing long-running tasks in your Activity is forbidden, so if the user sends your application to the background while an upload is in progress, the system might kill the process at some point and the file will never be uploaded
  • Upload management: with the upload API you can't just cancel a running upload, you can't efficiently perform multiple uploads unless you have implemented it in a separate Thread.

At some point, you will have to implement the upload API in a dedicated Thread or an Executor or, even better with Kotlin coroutines. It might be a lengthy task if you are not familiar with these components. A Thread won't be able to handle uploads when the application is in the background. If you are already familiar with Android Services, you know that implementing a Service is a good solution for this kind of issue. Let's have a deeper look at this component.

1. Android Service

According to Android documentation:

"A Service is an application component that can perform long-running operations in the background. It does not provide a user interface. Once started, a service might continue running for some time, even after the user switches to another application. Additionally, a component can bind to a service to interact with it and perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider from the background."

Nice!

There is another interesting part about the service:

"When a service is running, it can notify the user of events using snack bar notifications or status bar notifications."

For a type of service called Foreground Service, your service must display a notification. The notification can look like a text, but it can also be an audio player.

When you start looking for Service notifications, they are everywhere.

Service notifications - Android app

Why am I talking about notifications? Because it would be nice to have a notification showing the upload's progress. Right? Like this:

Progress notification example

Progress notification example

So, if your application requires uploading files to api.video, the solution would be to call the upload API from an Android Service.

I have an excellent news for you: the Android API client and the Android video uploader comes with a fully customizable Service whose purpose is to upload files, called UploadService.

2. api.video UploadService

The UploadService is the easiest way to upload video files to api.video on Android. It supports:

  • upload with video id
  • upload with upload token
  • progressive upload
  • progress notification of the upload of the current file
  • success notification
  • error notification
  • multiple uploads: it uploads files from an internal queue
  • cancel the upload of a specific file or all files

Here is a small video to show how it’s used in the ‣ example:

UploadService example

UploadService notification customization

The UploadService comes with many levels of notification customization:

  • Notification color and icon
  • Notification messages
  • Notification itself. You can choose not to display progress or to display the name of the file currently being uploaded. For example, notifications could have a Stop button.

To customize the UploadService, the first step is to extend the UploadService:

class MyUploadService : UploadService(
    notificationId = 1234, // A unique int
    channelId = "video.api.uploader.service" // A unique string
)

If you have a closer look at the UploadService constructor, you will notice that you can change the notification icon and color with:

class MyColorfullUploadService : UploadService(
    notificationId = 1234, // A unique int
    channelId = "video.api.uploader.service", // A unique string
		notificationIconResourceId = R.drawable.ic_icon, // A custom drawable
		notificationColorResourceId = R.color.my_favorite_color // A color resource
)

To have more controls over the notification, you can override onUploadProgressNotification, onUploadErrorNotification, onUploadStartedNotification, onUploadCancelledNotification, onUploadSuccessNotification, onLastUploadNotification.

class MyColorfullUploadService : UploadService(...) {
	override fun onUploadSuccessNotification(id: String /* Unique upload id */, video: Video): Notification {
	      // Create a notification with NotificationCompat builder
        return NotificationCompat.Builder(this, channelId)
            .setStyle(notificationIconResourceId, notificationColorResourceId)
            .setContentTitle(getString(R.string.upload_success_notification_text))
            .build()
    }
}

There is a solution for each of your requirements!

Implementation

As with every service, you have to declare it in the AndroidManifest.xml

<application>
	<service android:name=".MyColorfullUploadService" />
</application>

As the UploadService is a Foreground Service (a special type of service), you also have to add:

<manifest>
	<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
	<!--For Android >= API 33: -->
	<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
</manifest>

Nice. We are almost done. You have to start it and bind it. Fortunately, there is a static API to simplify its usage:

UploadService.startService(
    this,
    MyColorfullUploadService::class.java, // Your custom service class
    apiKey = "YOUR_API_KEY", // Could be null for upload with upload token
    onServiceCreated = { service ->
       // Keep and use the service here :)
    },
    onServiceDisconnected = { Log.e(TAG, "Upload service has been disconnected") }
)

As startService binds your application to the UploadService, you must call UploadService.unbindService when your application is put to background.

Once you have access to the service, you can call upload API for a video id

service.upload("YOUR_VIDEO_ID", yourFilePath)

Or for an upload token:

service.uploadWithUploadToken("YOUR_UPLOAD_TOKEN", yourFilePath)

Conclusion

With the UploadService, uploading a video to api.video has never been this easy! For a complete example with the UploadService, check out the ‣ example.

And we're done! To start building right now, check out our docs and sign up for a free account

Thibault Beyou

Senior Mobile Developer

Create your free account

Start building with video now