Cloudinary Blog

Addressing mobile challenges with the new Cloudinary SDK for Android

CloudinaryAndroid SDK

Developing applications for mobile consumption requires facing, and overcoming, some difficult challenges. Apps need to limit their RAM, CPU and battery usage while still performing the required tasks in a reasonable time frame. If too many background tasks are running, the mobile device can become sluggish, with the battery running out very quickly. Coordination with other apps is crucial to keep the device responsive and make the battery last longer.

Networks on mobile devices are also often unstable. Especially in some areas, disconnections are frequent and there are many switches between different network nodes, as well as slow network performance with a high percentage of packet loss. Apps need to be able to handle all the network issues, and if necessary, network activity needs to fail smoothly and resume when the network is available again, automatically if possible.

To support higher resolution mobile devices, the app backend needs to serve high-quality images and videos. Those resources take longer to download, and also consume more CPU and RAM to decode and then display on screen. On the other hand, for a low-resolution mobile device those are wasted resources, because you only need a low-quality resource. So you need to maintain a lot of different versions for each of your resources and then determine which one is most appropriate to serve to each mobile device.

With all that in mind, Cloudinary's latest version of the Android SDK lets you easily implement background upload functionality in your app to ensure the best user experience. If the user is doing something CPU, RAM or power intensive, the uploads can be paused so that the user experience doesn't suffer, and then continue when conditions are more favorable. And with Cloudinary's Dynamic URL feature, the delivered resource can be generated on the fly, eliminating the need to pre-generate all the various versions of your resources for different mobile devices.

The Cloudinary Android SDK v2.0

The Cloudinary SDK works on the principle that Android knows how to manage its own memory, CPU and power, and so relies on the operating system itself doing the prioritization of those limited hardware resources. All uploads are presented as requests to the operating system, which will schedule the uploads accordingly. The Cloudinary SDK hooks into Android's JobScheduler, which makes sure the mobile device works smoothly when running background uploads. If the mobile device is running an older version of Android that does not support the JobScheduler API, then the Cloudinary SDK transparently falls back to using the scheduling engine inside Google Play services.

All upload requests can be finely-tuned using the new policy mechanism, and the SDK can handle global callbacks, even when your app is down, or is running in the background.

Presenting the Cloudinary MediaManager

The Cloudinary Android SDK v2.0 provides you with the MediaManager class, with methods for configuring and handling all your media-related operations. Use the upload method to build your request, which is then dispatched to a background queue via the MediaManager's dispatch method.

MediaManager.get().upload(imageFile).dispatch();

The MediaManager's option method lets you include any upload parameters for Cloudinary, for example, adding the tag user_uploaded:

MediaManager.get().upload(imageFile)
   .option("tags", "user_uploaded")
   .dispatch();

While you are at it, you might want to specify some upload conditions in your request, such as how many times to retry after a recoverable error (e.g., network issues), to limit the upload to a wifi network, or only when the device is charging. The MediaManager's policy method lets you do just that, overriding the default values for that particular upload request:

MediaManager.get().upload(filePath)
   .policy(new UploadPolicy.Builder()
      .maxRetries(7)
      .requiresCharging(true)
      .networkPolicy(UploadPolicy.NetworkType.UNMETERED)
      .build())
   .dispatch();

Callbacks

Since all uploads are ultimately run asynchronously by the system, the MediaManager's callback method provides an easy way to hook into the upload's progress and provide specific code to run at each stage of the upload.

String requestId = MediaManager.get().upload(filePath)
   .callback(new UploadCallback() {
      @Override
      public void onProgress(String requestId, long bytes, long totalBytes) {
         Double progress = (double) bytes/totalBytes;
         // post progress to app UI (e.g. progress bar, notification)
      }
      @Override
      public void onSuccess(String requestId, Map resultData) {
      }
    ...
   })
   .dispatch();

This method of implementing callbacks won't suffice if your app is down or is running in the background. In this case, you would want to implement global callbacks for your app by registering a new service class that extends the provided ListenerService class. All upload request callbacks will be routed to your service, which implements the code to run at each stage of the upload.

public class MyClass extends ListenerService {
   @Override
   public void onProgress(String requestId, long bytes, long totalBytes) {
      Double progress = (double) bytes/totalBytes;
      // post progress to app UI (e.g. progress bar, notification)
   }
   @Override
   public void onSuccess(String requestId, Map resultData) {
   }
   ...
}

Not only upload

Once your media assets have been uploaded to Cloudinary, you can take advantage of Cloudinary's Dynamic URL feature to deliver your images and videos to your users. Dynamic URLs include instructions telling Cloudinary how to transform and optimize the asset on-the-fly, and then deliver it through a fast CDN to the end user for optimal user experience. There is no need to pre-generate all the different versions you may need for the various devices running your app.

Besides taking care of all your resource uploads directly to your Cloudinary account, the MediaManager class provides the url method to generate a URL string for accessing resources uploaded to your Cloudinary account:

MediaManager.get().url().generate("sample.jpg")
// returns: http://res.cloudinary.com/demo/image/upload/sample.jpg

You can also call the transformation method to include any transformation instructions in the generated URL:

Android:
MediaManager.get().url().transformation(new Transformation()
  .gravity("face").radius(75).border("10px_solid_grey").crop("crop").chain()
  .overlay("couple").width(170).height(150).radius("max").gravity("faces").border("3px_solid_black").crop("thumb").chain()
  .flags("layer_apply").gravity("north_east")).generate("woman2.jpg")
image cropped with face detection and given rounded corners and a grey border, with an overlay of the image of `couple` resized to an oval thumbnail with face detection and a black border added to the northeast corner

Summary

The new version of the Cloudinary SDK for Android is a major release that now makes it simple to include upload functionality in your mobile app, and let your users upload their media directly to your Cloudinary account. The SDK takes advantage of Android's built-in functionality when executing the uploads, to make sure that your users enjoy an uninterrupted experience while using your app. Integrating with Cloudinary to upload, manage, and deliver all your app resources is now easier than ever. Make sure you check out the Android integration documentation, and if you don't already have a Cloudinary account, you can sign up for free.

Recent Blog Posts

How the Right Tools and Training Drive SDR Success

Here at Cloudinary, I head a team of eight SDRs, who are responsible for creating the first impression potential customers have of our company’s brand. In just the first 10 months of 2017, our team of outbound SDRs have been responsible for sending more than 67,000 personalized emails and making more than 15,000 calls.

Read more
The JS video player that developers will love (How To)

It doesn't take a genius (or a statistician) to know that video represents a significant proportion of web and mobile content these days. But did you realize that in 2017, video will account for about 75% of all internet traffic and that 55% of people watch videos online every day? In fact, 52% of marketing professionals worldwide believe that video is the content type with the best ROI, with people spending up to 2.6x more time on pages with video than on those without.

Read more
 Beyond Drupal Media: Make Images and Video Fly with Cloudinary

Drupal is a very popular open source content management system (CMS) that has been deployed countless times by organizations and developers around the world. Drupal gained a reputation for being very flexible, powerful and robust in creating complex websites. With Drupal, you can create everything from plain websites, blogs and forums to ambitious enterprise systems.

Read more
Curbing Terrorist Content Online

Today, Cloudinary is proud to announce that it has joined The Global Internet Forum to Counter Terrorism (GIFCT), to help fight the spread of terrorist and violent extremist content on the Internet. The forum was established by Facebook, Microsoft, Twitter and YouTube in mid-2017. Cloudinary will contribute to the hash-sharing database, which all contributing companies can use to help identify and block terrorist related images and videos upon upload.

Read more
Introducing the complete video solution for developers

Videos in web sites and apps are starting to catch up with images in terms of popularity and they are a constantly growing part of the media strategy for most organizations. This means bigger challenges for developers who need to handle these videos in their web sites and mobile apps. Cloudinary's mission is to solve all developer needs around image and video management. In this blog post, we are excited to introduce Cloudinary's complete cloud-based video management solution for developers.

Read more
Getting Started with StencilJS

Stencil is basically a compiler, not necessarily a UI library. A compiler that transforms TSX (TypeScript + JSX) into self-contained custom components.

Before you start learning about the tool, it’s important to note that Stencil is not another heavy JavaScript framework you need to learn. If you have worked with Angular or React, or understand web components, then Stencil is worth a look.

Read more