### Example Server Response for Upload Authorization
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
An example JSON response from a server-side upload authorization request. It includes the signature, public ID, timestamp, and API key required for signed uploads.
```json
{
"signature": "sgjfdoigfjdgfdogidf9g87df98gfdb8f7d6gfdg7gfd8",
"public_id": "abdbasdasda76asd7sa789",
"timestamp": 1346925631,
"api_key": "123456789012345"
}
```
--------------------------------
### Initialize MediaManager with Configuration
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Initialize the MediaManager with configuration parameters, including cloud_name, in your Application.onCreate().
```java
Map config = new HashMap();
config.put("cloud_name", "myCloudName");
MediaManager.init(this, config);
```
--------------------------------
### Initialize SDK with SignatureProvider for Signed Uploads
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Initialize the SDK with a SignatureProvider for server-side signing. The provideSignature method should call your backend to obtain the signature, API key, and timestamp. This method runs on a background thread, so blocking calls are safe.
```java
MediaManager.init(this, new SignatureProvider() {
@Override
public Signature provideSignature(Map options) {
// Call your backend to get signature, timestamp, api_key
// This runs on a background thread — blocking calls are safe here
return new Signature(serverSignature, apiKey, timestamp);
}
@Override
public String getName() {
return "MyServerSigner";
}
}, config);
```
--------------------------------
### Initialize SDK via AndroidManifest.xml
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Configure the SDK by adding the CLOUDINARY_URL metadata to your AndroidManifest.xml. No explicit code configuration is needed in Application.onCreate() if this option is used.
```xml
```
```java
MediaManager.init(this);
```
--------------------------------
### Load Image with Fresco Backend
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Switch to the Fresco backend. Load an image with specific transformations for radius, width, height, and crop.
```java
MediaManager.get().setDownloadRequestBuilderFactory(new FrescoDownloadRequestBuilderFactory());
MediaManager.get().download(context)
.load("avatars/user_42")
.transformation(new Transformation().radius("max").width(100).height(100).crop("fill"))
.into(imageView);
```
--------------------------------
### Preprocess Uploads with ImagePreprocessChain
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Run transformations on local assets before uploading. Requires a Context for dispatching. Use built-in chains or create custom ones.
```java
// Limit image to max 1024x1024 before uploading (retains aspect ratio)
ImagePreprocessChain chain = ImagePreprocessChain.limitDimensionsChain(1024, 1024);
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.preprocess(chain)
.dispatch(context); // Context required when using preprocess
```
```java
// Custom chain: crop then limit dimensions
ImagePreprocessChain customChain = new ImagePreprocessChain()
.addStep(new Crop(new Point(50, 50), new Point(500, 500)))
.addStep(new Limit(800, 800));
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.preprocess(customChain)
.dispatch(context);
```
```java
// Enforce a maximum file size (fails the upload if exceeded)
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.maxFileSize(2 * 1024 * 1024L) // 2 MB limit
.dispatch(context);
```
--------------------------------
### MediaManager.init()
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Initializes the Cloudinary SDK. This method must be called once in your Application's onCreate() method before any other SDK operations. It supports multiple configuration methods.
```APIDOC
## MediaManager.init()
### Description
The entry point of the entire SDK. Must be called once in `Application.onCreate()` before any other operation. Accepts a map-based config, a `Configuration` object, or reads `CLOUDINARY_URL` from `AndroidManifest.xml` metadata. Throws `IllegalStateException` if called more than once.
### Method
`MediaManager.init(Context context, Map config)`
`MediaManager.init(Context context)`
`MediaManager.init(Context context, SignatureProvider signatureProvider, Map config)`
### Parameters
#### Programmatic Config (Option 1)
- **context** (Context) - The application context.
- **config** (Map) - A map containing configuration options. At a minimum, `cloud_name` is required. Do not include `api_secret` in mobile apps.
#### AndroidManifest.xml Metadata (Option 2)
- **context** (Context) - The application context.
*Configuration is read from `AndroidManifest.xml` via ``*
#### Signed Uploads (Option 3)
- **context** (Context) - The application context.
- **signatureProvider** (SignatureProvider) - An object implementing the `SignatureProvider` interface to provide signatures for uploads.
- **config** (Map) - A map containing configuration options.
### Request Example
```java
// Option 1: Programmatic config (cloud_name only — never include api_secret in mobile apps)
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Map config = new HashMap<>();
config.put("cloud_name", "my_cloud_name");
MediaManager.init(this, config);
}
}
// Option 2: Via AndroidManifest.xml metadata (no code config needed)
// In AndroidManifest.xml:
//
// Then in Application.onCreate():
MediaManager.init(this);
// Option 3: With a SignatureProvider for signed uploads (server-side signing)
MediaManager.init(this, new SignatureProvider() {
@Override
public Signature provideSignature(Map options) {
// Call your backend to get signature, timestamp, api_key
// This runs on a background thread — blocking calls are safe here
return new Signature(serverSignature, apiKey, timestamp);
}
@Override
public String getName() {
return "MyServerSigner";
}
}, config);
```
### Response
This method does not return a value but throws `IllegalStateException` if called more than once.
```
--------------------------------
### Initialize MediaManager with Manifest Configuration
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Initialize the MediaManager using the CLOUDINARY_URL meta-data property in AndroidManifest.xml. No programmatic configuration is required.
```xml
...
...
```
--------------------------------
### Upload File with Default Settings and Callback
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Uploads a File using default settings, an upload preset, and a request-specific callback. The returned request ID can be used for global callbacks or cancellation.
```java
String requestId = MediaManager.get().upload(imageFile).unsigned("sample_preset").callback(callback).dispatch();
```
--------------------------------
### Load Image with Picasso Backend
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Switch to the Picasso backend. Load an image using a public ID and apply responsive transformations.
```java
MediaManager.get().setDownloadRequestBuilderFactory(new PicassoDownloadRequestBuilderFactory());
MediaManager.get().download(context)
.load("landscapes/mountains")
.responsive(ResponsiveUrl.Preset.FIT)
.into(imageView);
```
--------------------------------
### Generate Responsive Image URLs with Presets
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Use MediaManager's responsiveUrl method with presets like AUTO_FILL or FIT to generate Cloudinary URLs that adapt to ImageView dimensions. The generated URL is provided via a callback.
```java
// Using a preset directly on MediaManager
ImageView imageView = findViewById(R.id.my_image);
MediaManager.get().responsiveUrl(
imageView,
"portraits/sample", // Cloudinary public ID
ResponsiveUrl.Preset.AUTO_FILL, // fill + auto gravity
url -> imageView.setImageUrl(url.generate()) // callback when URL is ready
);
// Using a Preset via DownloadRequestBuilder (recommended pattern)
MediaManager.get().download(context)
.load("portraits/sample")
.responsive(ResponsiveUrl.Preset.FIT)
.into(imageView);
```
--------------------------------
### Initialize SDK with Programmatic Config
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Initialize the SDK with a map containing the cloud name. Never include the API secret in mobile apps. This code should be placed in your Application's onCreate() method.
```java
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Map config = new HashMap<>();
config.put("cloud_name", "my_cloud_name");
MediaManager.init(this, config);
}
}
```
--------------------------------
### Load Image with Glide Backend
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Register Glide as the download backend once. Load a Cloudinary public ID with transformations, a placeholder, and a callback for success or error.
```java
MediaManager.get().setDownloadRequestBuilderFactory(new GlideDownloadRequestBuilderFactory());
ImageView imageView = findViewById(R.id.product_image);
MediaManager.get().download(context)
.load("products/shoe_001") // Cloudinary public ID
.transformation(new Transformation()
.width(400).height(400).crop("fill"))
.placeholder(R.drawable.loading_placeholder)
.callback(new DownloadRequestCallback() {
@Override public void onSuccess() {
Log.d("Download", "Image loaded successfully");
}
@Override public void onError(ErrorInfo error) {
Log.e("Download", "Failed: " + error.getDescription());
}
})
.into(imageView);
```
--------------------------------
### Upload URI with Immediate Constraint and Network Policy
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Uploads a local Uri resource with specific upload policies: immediate execution, a maximum of 7 retries, and requiring an unmetered network connection.
```java
String requestId = MediaManager.get().upload(uri)
.unsigned("sample_app_preset")
.constrain(TimeWindow.immediate())
.policy(new RequestUploadPolicy.Builder().maxRetries(7).networkPolicy(RequestUploadPolicy.NetworkType.UNMETERED).build())
.dispatch();
```
--------------------------------
### Server-Based Signature Provider Initialization
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Initializes the MediaManager with a custom SignatureProvider. This provider is responsible for obtaining upload signatures from a server endpoint, enhancing security for uploads.
```java
MediaManager.init(this, new SignatureProvider() {
@Override
public Signature provideSignature(Map options) {
// call server signature endpoint
}
}, null);
```
--------------------------------
### Unsigned Upload with Upload Preset
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Uploads a local resource (as a Uri) using an existing upload preset. This method is used for unsigned uploads where rules are pre-defined in the Cloudinary console.
```java
String requestId = MediaManager.get().upload(uri).unsigned("sample_preset").dispatch();
```
--------------------------------
### Configure Upload Policy with UploadPolicy.Builder
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Set network type, retry behavior, and device state requirements for uploads using UploadPolicy.Builder. Defaults to exponential backoff with 5 retries.
```java
UploadPolicy policy = new UploadPolicy.Builder()
.networkPolicy(UploadPolicy.NetworkType.UNMETERED)
.maxRetries(10)
.backoffCriteria(60_000L, UploadPolicy.BackoffPolicy.LINEAR)
.requiresCharging(false)
.requiresIdle(false)
.build();
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.policy(policy)
.dispatch();
```
--------------------------------
### Generate Face Detection Thumbnail URL (Kotlin)
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Generate a URL for an uploaded image using Kotlin, creating a 90x90 face-detection-based thumbnail.
```kotlin
MediaManager.get().url().transformation(Transformation>().width(90).height(90).crop("thumb").gravity("face")).generate("woman.jpg")
```
--------------------------------
### Generate Custom Responsive Image URLs
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Create custom responsive URLs with fine-grained control over step size, minimum and maximum dimensions. Load the generated URL into an ImageView using an image loading library like Glide.
```java
// Custom responsive URL with fine-grained control
ResponsiveUrl responsiveUrl = MediaManager.get()
.responsiveUrl(true, true, "fill", "auto")
.stepSize(100)
.minDimension(200)
.maxDimension(1200);
Url baseUrl = MediaManager.get().url().publicId("hero/banner");
responsiveUrl.generate(baseUrl, imageView, url -> {
String finalUrl = url.generate();
// Load finalUrl into ImageView using Glide/Picasso/Fresco
Glide.with(context).load(finalUrl).into(imageView);
});
```
--------------------------------
### UploadRequest.preprocess()
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Attaches a PreprocessChain to transform local assets before uploading. This includes built-in chains for dimension limiting and cropping, as well as custom chains.
```APIDOC
## UploadRequest.preprocess() — Preprocess Before Upload
Attaches a `PreprocessChain` that runs transformations on the local asset before uploading. The built-in `ImagePreprocessChain` works on `Bitmap` objects with steps for dimension limiting, cropping, custom encode/decode. Preprocessing requires passing a `Context` to `dispatch()`.
```java
// Limit image to max 1024x1024 before uploading (retains aspect ratio)
ImagePreprocessChain chain = ImagePreprocessChain.limitDimensionsChain(1024, 1024);
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.preprocess(chain)
.dispatch(context); // Context required when using preprocess
// Custom chain: crop then limit dimensions
ImagePreprocessChain customChain = new ImagePreprocessChain()
.addStep(new Crop(new Point(50, 50), new Point(500, 500)))
.addStep(new Limit(800, 800));
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.preprocess(customChain)
.dispatch(context);
// Enforce a maximum file size (fails the upload if exceeded)
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.maxFileSize(2 * 1024 * 1024L) // 2 MB limit
.dispatch(context);
```
```
--------------------------------
### Constrain Upload Execution with TimeWindow
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Control when uploads can execute using TimeWindow. Use TimeWindow.immediate() for instant execution or define custom min latency and max deadline.
```java
String requestId = MediaManager.get()
.upload(imageFile)
.unsigned("my_preset")
.constrain(TimeWindow.immediate())
.dispatch();
```
```java
TimeWindow window = new TimeWindow.Builder()
.minLatencyMillis(5 * 60 * 1000L)
.maxExecutionDelayMillis(60 * 60 * 1000L)
.build();
String requestId = MediaManager.get()
.upload(imageFile)
.unsigned("my_preset")
.constrain(window)
.dispatch();
```
```java
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.startNow(context); // requires Context, runs immediately
```
--------------------------------
### Set Global Upload Policy Defaults
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Configure app-wide default upload behaviors like concurrent uploads, network requirements, and retry limits. Individual requests can override these defaults.
```java
// Allow up to 3 concurrent uploads, require WiFi, max 3 retries
GlobalUploadPolicy globalPolicy = new GlobalUploadPolicy.Builder()
.maxConcurrentRequests(3)
.networkPolicy(UploadPolicy.NetworkType.UNMETERED)
.maxRetries(3)
.backoffCriteria(30_000L, UploadPolicy.BackoffPolicy.EXPONENTIAL)
.build();
MediaManager.get().setGlobalUploadPolicy(globalPolicy);
// All subsequent uploads inherit this policy unless overridden per-request
MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.dispatch(); // uses WiFi + 3 retries from global policy
```
--------------------------------
### Generate Cloudinary Transformation URLs
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Construct CDN delivery URLs with chained transformations. No network calls are made. Supports various transformations like cropping, resizing, and overlays.
```java
// Fill crop to 300x200
String url = MediaManager.get().url()
.transformation(new Transformation()
.width(300).height(200).crop("fill"))
.generate("sample.jpg");
// → https://res.cloudinary.com/my_cloud/image/upload/w_300,h_200,c_fill/sample.jpg
```
```java
// Face-detection thumbnail, 90x90
String thumbUrl = MediaManager.get().url()
.transformation(new Transformation()
.width(90).height(90).crop("thumb").gravity("face"))
.generate("portraits/jane.jpg");
```
```java
// Chained transformation: resize then add watermark overlay
String watermarked = MediaManager.get().url()
.transformation(new Transformation()
.width(800).height(600).crop("fill").chain()
.overlay("company_logo").gravity("south_east").opacity(60))
.generate("products/item_001.jpg");
```
```java
// Facebook profile photo, fit to 130x130
String fbUrl = MediaManager.get().url()
.type("facebook")
.transformation(new Transformation()
.width(130).height(130).crop("fill").gravity("north_west"))
.generate("billclinton.jpg");
```
```kotlin
// Kotlin syntax
val ktUrl = MediaManager.get().url()
.transformation(Transformation>()
.width(200).height(200).crop("thumb").gravity("face"))
.generate("sample.jpg")
```
--------------------------------
### ResponsiveUrl for View-Size-Aware Image URLs
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Generates Cloudinary URLs that adapt image dimensions to the actual rendered size of an ImageView, using step-size quantization to limit CDN cache entries. Integrates via presets or custom parameters.
```APIDOC
## ResponsiveUrl — View-Size-Aware Image URLs
### Description
Generates Cloudinary URLs that adapt image dimensions to the actual rendered size of an `ImageView`. Uses step-size quantization to limit the number of unique transformations cached on the CDN. Integrates via presets (`AUTO_FILL`, `FIT`) or custom crop/gravity parameters.
### Usage with Presets
#### Using a preset directly on MediaManager
```java
ImageView imageView = findViewById(R.id.my_image);
MediaManager.get().responsiveUrl(
imageView,
"portraits/sample", // Cloudinary public ID
ResponsiveUrl.Preset.AUTO_FILL, // fill + auto gravity
url -> imageView.setImageUrl(url.generate()) // callback when URL is ready
);
```
#### Using a Preset via DownloadRequestBuilder (recommended pattern)
```java
MediaManager.get().download(context)
.load("portraits/sample")
.responsive(ResponsiveUrl.Preset.FIT)
.into(imageView);
```
### Custom Responsive URL Generation
#### With fine-grained control
```java
ResponsiveUrl responsiveUrl = MediaManager.get()
.responsiveUrl(true, true, "fill", "auto")
.stepSize(100)
.minDimension(200)
.maxDimension(1200);
Url baseUrl = MediaManager.get().url().publicId("hero/banner");
responsiveUrl.generate(baseUrl, imageView, url -> {
String finalUrl = url.generate();
// Load finalUrl into ImageView using Glide/Picasso/Fresco
Glide.with(context).load(finalUrl).into(imageView);
});
```
```
--------------------------------
### MediaManager.download() - Load Images into ImageView
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
This method creates a DownloadRequestBuilder to load images into an ImageView. It supports different image loading backends like Glide, Picasso, and Fresco. You can load images using a Cloudinary public ID or a full URL, apply transformations, set placeholders, and handle callbacks for success or error.
```APIDOC
## MediaManager.download()
### Description
Creates a `DownloadRequestBuilder` backed by Glide, Picasso, or Fresco (configured via `setDownloadRequestBuilderFactory`). Accepts a Cloudinary public ID or a full URL, applies transformations, and loads the result into an `ImageView`.
### Setup (Example with Glide)
```java
// Setup: register Glide as the download backend (once, in Application.onCreate())
MediaManager.get().setDownloadRequestBuilderFactory(new GlideDownloadRequestBuilderFactory());
```
### Usage Example (Cloudinary Public ID)
```java
// Load a Cloudinary public ID with a transformation
ImageView imageView = findViewById(R.id.product_image);
MediaManager.get().download(context)
.load("products/shoe_001") // Cloudinary public ID
.transformation(new Transformation()
.width(400).height(400).crop("fill"))
.placeholder(R.drawable.loading_placeholder)
.callback(new DownloadRequestCallback() {
@Override public void onSuccess() {
Log.d("Download", "Image loaded successfully");
}
@Override public void onError(ErrorInfo error) {
Log.e("Download", "Failed: " + error.getDescription());
}
})
.into(imageView);
```
### Usage Example (Picasso Backend)
```java
// Using Picasso backend
MediaManager.get().setDownloadRequestBuilderFactory(new PicassoDownloadRequestBuilderFactory());
MediaManager.get().download(context)
.load("landscapes/mountains")
.responsive(ResponsiveUrl.Preset.FIT)
.into(imageView);
```
### Usage Example (Fresco Backend)
```java
// Using Fresco backend
MediaManager.get().setDownloadRequestBuilderFactory(new FrescoDownloadRequestBuilderFactory());
MediaManager.get().download(context)
.load("avatars/user_42")
.transformation(new Transformation().radius("max").width(100).height(100).crop("fill"))
.into(imageView);
```
```
--------------------------------
### MediaManager.get().upload()
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
The primary upload API. Accepts a File path, Uri, byte[], or Android raw resource ID. Returns an UploadRequest builder that is configured via chaining before calling dispatch() to enqueue the upload in the background. Returns a unique requestId string to track or cancel the request.
```APIDOC
## MediaManager.get().upload()
### Description
Uploads files to Cloudinary using various input types like file paths, Uris, byte arrays, or raw resource IDs. Returns an `UploadRequest` builder for further configuration.
### Method
`MediaManager.get().upload(Object source)`
### Parameters
#### Source
- **source** (Object) - Required - Can be a String (file path), Uri, byte[], or an Android raw resource ID (e.g., R.raw.my_video).
### Configuration Options (Chained before dispatch())
- **unsigned(String uploadPresetName)**: Configures the upload to use an unsigned preset.
- **option(String key, Object value)**: Sets additional upload options (e.g., "public_id", "tags", "resource_type").
- **callback(UploadCallback callback)**: Attaches a callback to monitor upload progress and status.
- **policy(UploadPolicy policy)**: Configures upload constraints like network type and retry behavior.
- **constrain(TimeWindow timeWindow)**: Sets a time window for when the upload is allowed to execute.
- **startNow(Context context)**: Forces immediate foreground execution (requires Context).
### Dispatch
- **dispatch()**: Enqueues the upload request to be processed in the background. Returns a unique `requestId` string.
### Request Example (File Path)
```java
String requestId = MediaManager.get()
.upload("/sdcard/Pictures/photo.jpg")
.unsigned("my_upload_preset")
.option("public_id", "user_photos/profile_001")
.option("tags", "android,profile")
.callback(new UploadCallback() {
@Override public void onStart(String requestId) { /* ... */ }
@Override public void onProgress(String requestId, long bytes, long totalBytes) { /* ... */ }
@Override public void onSuccess(String requestId, Map resultData) { /* ... */ }
@Override public void onError(String requestId, ErrorInfo error) { /* ... */ }
@Override public void onReschedule(String requestId, ErrorInfo error) { /* ... */ }
})
.dispatch();
```
### Request Example (Uri)
```java
Uri imageUri = data.getData(); // from onActivityResult
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_upload_preset")
.dispatch();
```
### Request Example (Byte Array)
```java
byte[] imageBytes = getBitmapBytes();
String requestId = MediaManager.get()
.upload(imageBytes)
.unsigned("my_upload_preset")
.option("resource_type", "image")
.dispatch();
```
### Request Example (Raw Resource)
```java
String requestId = MediaManager.get()
.upload(R.raw.intro_video)
.unsigned("video_preset")
.option("resource_type", "video")
.dispatch();
```
### Request Example (Cancel Request)
```java
boolean cancelled = MediaManager.get().cancelRequest(requestId);
```
### Request Example (Cancel All Requests)
```java
int numCancelled = MediaManager.get().cancelAllRequests();
```
```
--------------------------------
### MediaManager.get().url()
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Generates Cloudinary transformation URLs by chaining transformations fluently. This method constructs URLs without making network calls.
```APIDOC
## MediaManager.get().url() — Generate Transformation URLs
Returns a Cloudinary `Url` builder for constructing CDN delivery URLs with transformations. Transformations are chained fluently and encoded into the URL path. No network call is made — this is purely URL construction.
```java
// Fill crop to 300x200
String url = MediaManager.get().url()
.transformation(new Transformation()
.width(300).height(200).crop("fill"))
.generate("sample.jpg");
// → https://res.cloudinary.com/my_cloud/image/upload/w_300,h_200,c_fill/sample.jpg
// Face-detection thumbnail, 90x90
String thumbUrl = MediaManager.get().url()
.transformation(new Transformation()
.width(90).height(90).crop("thumb").gravity("face"))
.generate("portraits/jane.jpg");
// Chained transformation: resize then add watermark overlay
String watermarked = MediaManager.get().url()
.transformation(new Transformation()
.width(800).height(600).crop("fill").chain()
.overlay("company_logo").gravity("south_east").opacity(60))
.generate("products/item_001.jpg");
// Facebook profile photo, fit to 130x130
String fbUrl = MediaManager.get().url()
.type("facebook")
.transformation(new Transformation()
.width(130).height(130).crop("fill").gravity("north_west"))
.generate("billClinton.jpg");
// Kotlin syntax
val ktUrl = MediaManager.get().url()
.transformation(Transformation>()
.width(200).height(200).crop("thumb").gravity("face"))
.generate("sample.jpg")
```
```
--------------------------------
### Upload Files to Cloudinary with MediaManager
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Upload files using various input types like file paths, Uris, byte arrays, or raw resource IDs. Configure upload options and handle callbacks for status updates. Returns a requestId for tracking or cancellation.
```java
String requestId = MediaManager.get()
.upload("/sdcard/Pictures/photo.jpg")
.unsigned("my_upload_preset")
.option("public_id", "user_photos/profile_001")
.option("tags", "android,profile")
.callback(new UploadCallback() {
@Override public void onStart(String requestId) {
Log.d("Upload", "Started: " + requestId);
}
@Override public void onProgress(String requestId, long bytes, long totalBytes) {
int pct = (int) (bytes * 100 / totalBytes);
Log.d("Upload", "Progress: " + pct + "%");
}
@Override public void onSuccess(String requestId, Map resultData) {
String publicId = (String) resultData.get("public_id");
String secureUrl = (String) resultData.get("secure_url");
Log.d("Upload", "Success! URL: " + secureUrl);
}
@Override public void onError(String requestId, ErrorInfo error) {
Log.e("Upload", "Error " + error.getCode() + ": " + error.getDescription());
}
@Override public void onReschedule(String requestId, ErrorInfo error) {
Log.w("Upload", "Rescheduled due to: " + error.getDescription());
}
})
.dispatch();
```
```java
Uri imageUri = data.getData(); // from onActivityResult
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_upload_preset")
.dispatch();
```
```java
byte[] imageBytes = getBitmapBytes();
String requestId = MediaManager.get()
.upload(imageBytes)
.unsigned("my_upload_preset")
.option("resource_type", "image")
.dispatch();
```
```java
String requestId = MediaManager.get()
.upload(R.raw.intro_video)
.unsigned("video_preset")
.option("resource_type", "video")
.dispatch();
```
--------------------------------
### Generate Face Detection Thumbnail URL
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Generate a URL for an uploaded image, creating a 90x90 face-detection-based thumbnail.
```java
MediaManager.get().url().transformation(new Transformation().width(90).height(90).crop("thumb").gravity("face")).generate("woman.jpg")
```
--------------------------------
### Generate Transformed Image URL
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Generate a URL for an uploaded image, applying transformations to resize and crop it to a 100x150 rectangle.
```java
MediaManager.get().url().transformation(new Transformation().width(100).height(150).crop("fill")).generate("sample.jpg")
```
--------------------------------
### Implement ListenerService for Background Uploads
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Extend ListenerService to handle upload callbacks even when the app is in the background or killed. Declare the service in AndroidManifest.xml with the cloudinaryCallbackService metadata.
```java
// MyUploadListenerService.java
public class MyUploadListenerService extends ListenerService {
@Override
public void onStart(String requestId) {
// Upload began (app may be in background)
}
@Override
public void onProgress(String requestId, long bytes, long totalBytes) {
// Not called in background service context
}
@Override
public void onSuccess(String requestId, Map resultData) {
String publicId = (String) resultData.get("public_id");
// Save to DB, show notification, etc.
NotificationHelper.showSuccess(this, publicId);
}
@Override
public void onError(String requestId, ErrorInfo error) {
NotificationHelper.showError(this, error.getDescription());
}
@Override
public void onReschedule(String requestId, ErrorInfo error) { }
@Override
public IBinder onBind(Intent intent) { return null; }
}
```
```xml
```
--------------------------------
### Register Global Upload Callback
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Register a global UploadCallback to receive events for all uploads. Ensure to unregister it when the component is destroyed to prevent memory leaks.
```java
UploadCallback globalCallback = new UploadCallback() {
@Override public void onStart(String requestId) {
showUploadingNotification(requestId);
}
@Override public void onProgress(String requestId, long bytes, long totalBytes) {
updateNotificationProgress(requestId, bytes, totalBytes);
}
@Override public void onSuccess(String requestId, Map resultData) {
dismissNotification(requestId);
String url = (String) resultData.get("secure_url");
saveUrlToDatabase(url);
}
@Override public void onError(String requestId, ErrorInfo error) {
showErrorNotification(requestId, error.getDescription());
}
@Override public void onReschedule(String requestId, ErrorInfo error) {
// Upload will retry later; optionally update UI
}
};
// Register in onResume() or onCreate()
MediaManager.get().registerCallback(globalCallback);
// Unregister in onPause() or onDestroy()
MediaManager.get().unregisterCallback(globalCallback);
```
--------------------------------
### Upload URI with Custom Public ID
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Uploads a resource identified by a Uri and assigns it a specific public ID. This allows for predictable naming of uploaded assets.
```java
String requestId = MediaManager.get().upload(uri).unsigned("sample_preset").option("public_id", "sample_remote").dispatch();
```
--------------------------------
### UploadRequest.constrain()
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Constrains when a request is allowed to execute using a TimeWindow. TimeWindow.immediate() forces execution within the next second regardless of policy.
```APIDOC
## UploadRequest.constrain()
### Description
Sets a time window during which an upload request is permitted to execute, overriding other policy constraints if necessary. This allows for fine-grained control over when uploads occur.
### Method
`.constrain(TimeWindow timeWindow)` or `.startNow(Context context)`
### Parameters
#### timeWindow
- **timeWindow** (TimeWindow) - Required - An instance of `TimeWindow` configured using `TimeWindow.Builder` or predefined constants.
### TimeWindow Configuration
- **TimeWindow.immediate()**: Forces execution within the next second, bypassing other policy constraints.
- **TimeWindow.getDefault()**: Allows execution within a default window of up to 3 hours.
- **TimeWindow.Builder**: Used to create custom time windows.
- **minLatencyMillis(long minLatencyMillis)**: The minimum delay before the upload can start.
- **maxExecutionDelayMillis(long maxExecutionDelayMillis)**: The maximum deadline by which the upload must complete.
- **build()**: Creates the `TimeWindow` object.
### Special Method
- **startNow(Context context)**: A shortcut to force immediate foreground execution. Requires an Android `Context`.
### Request Example (Immediate Execution)
```java
String requestId = MediaManager.get()
.upload(imageFile)
.unsigned("my_preset")
.constrain(TimeWindow.immediate())
.dispatch();
```
### Request Example (Custom Time Window)
```java
TimeWindow window = new TimeWindow.Builder()
.minLatencyMillis(5 * 60 * 1000L) // Start after 5 minutes
.maxExecutionDelayMillis(60 * 60 * 1000L) // Must run within 1 hour
.build();
String requestId = MediaManager.get()
.upload(imageFile)
.unsigned("my_preset")
.constrain(window)
.dispatch();
```
### Request Example (Force Foreground Execution)
```java
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.startNow(context); // requires Context, runs immediately
```
```
--------------------------------
### UploadRequest.policy()
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Attaches an UploadPolicy to a request to control network type, retry behaviour, and device state requirements. Uses a builder with exponential backoff by default.
```APIDOC
## UploadRequest.policy()
### Description
Configures upload policies for a request, controlling network conditions, retry attempts, and device state requirements. Defaults to exponential backoff with 5 retries and a 2-minute initial backoff.
### Method
`.policy(UploadPolicy policy)`
### Parameters
#### policy
- **policy** (UploadPolicy) - Required - An instance of `UploadPolicy` configured using `UploadPolicy.Builder`.
### UploadPolicy.Builder Configuration
- **networkPolicy(UploadPolicy.NetworkType type)**: Sets the required network type (e.g., `UNMETERED`, `ANY`).
- **maxRetries(int maxRetries)**: Specifies the maximum number of retry attempts.
- **backoffCriteria(long initialBackoffMillis, UploadPolicy.BackoffPolicy policy)**: Configures the backoff strategy (e.g., `LINEAR`, `EXPONENTIAL`).
- **requiresCharging(boolean requiresCharging)**: If true, the upload will only proceed when the device is charging.
- **requiresIdle(boolean requiresIdle)**: If true, the upload will only proceed when the device is idle.
- **build()**: Creates the `UploadPolicy` object.
### Request Example
```java
UploadPolicy policy = new UploadPolicy.Builder()
.networkPolicy(UploadPolicy.NetworkType.UNMETERED)
.maxRetries(10)
.backoffCriteria(60_000L, UploadPolicy.BackoffPolicy.LINEAR)
.requiresCharging(false)
.requiresIdle(false)
.build();
String requestId = MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.policy(policy)
.dispatch();
```
```
--------------------------------
### Gradle Dependency for Cloudinary Android SDK
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Add this dependency to your build.gradle file to include the Cloudinary Android SDK.
```gradle
implementation 'com.cloudinary:cloudinary-android:3.1.2'
```
--------------------------------
### ListenerService for Background Uploads
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Extend ListenerService to receive upload callbacks even when the app is in the background or has been killed. The service is auto-registered by Cloudinary and delivers callbacks via Intent. It must be declared in AndroidManifest.xml with a cloudinaryCallbackService metadata entry.
```APIDOC
## ListenerService — Background Upload Callbacks
### Description
Extend `ListenerService` to receive upload callbacks even when the app is not in the foreground or has been killed. The service is auto-registered by Cloudinary and delivers callbacks via `Intent`. It must be declared in `AndroidManifest.xml` with a `cloudinaryCallbackService` metadata entry.
### Java Implementation Example
```java
// MyUploadListenerService.java
public class MyUploadListenerService extends ListenerService {
@Override
public void onStart(String requestId) {
// Upload began (app may be in background)
}
@Override
public void onProgress(String requestId, long bytes, long totalBytes) {
// Not called in background service context
}
@Override
public void onSuccess(String requestId, Map resultData) {
String publicId = (String) resultData.get("public_id");
// Save to DB, show notification, etc.
NotificationHelper.showSuccess(this, publicId);
}
@Override
public void onError(String requestId, ErrorInfo error) {
NotificationHelper.showError(this, error.getDescription());
}
@Override
public void onReschedule(String requestId, ErrorInfo error) { }
@Override
public IBinder onBind(Intent intent) { return null; }
}
```
### AndroidManifest.xml Configuration
```xml
```
```
--------------------------------
### MediaManager.registerCallback() / unregisterCallback()
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Registers and unregisters a global UploadCallback to receive events for all upload requests. This is useful for global progress indicators or notifications and must be unregistered to prevent memory leaks.
```APIDOC
## MediaManager.registerCallback() / unregisterCallback()
### Description
Registers an `UploadCallback` that receives events for ALL upload requests. This is useful for showing a global progress indicator or notification. It must be unregistered when the component is destroyed to avoid memory leaks.
### Method Signature
```java
MediaManager.get().registerCallback(UploadCallback globalCallback);
MediaManager.get().unregisterCallback(UploadCallback globalCallback);
```
### Parameters
* `globalCallback` (UploadCallback) - The callback to register or unregister.
### Example Usage
```java
UploadCallback globalCallback = new UploadCallback() {
@Override public void onStart(String requestId) {
// Handle upload start
}
@Override public void onProgress(String requestId, long bytes, long totalBytes) {
// Handle upload progress
}
@Override public void onSuccess(String requestId, Map resultData) {
// Handle successful upload
}
@Override public void onError(String requestId, ErrorInfo error) {
// Handle upload error
}
@Override public void onReschedule(String requestId, ErrorInfo error) {
// Handle upload reschedule
}
};
// Register in onResume() or onCreate()
MediaManager.get().registerCallback(globalCallback);
// Unregister in onPause() or onDestroy()
MediaManager.get().unregisterCallback(globalCallback);
```
```
--------------------------------
### GlobalUploadPolicy
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Sets app-wide default upload behavior for all requests made through MediaManager. This includes controlling concurrent uploads, network requirements, and retry limits.
```APIDOC
## GlobalUploadPolicy — Set App-Wide Upload Defaults
Sets default upload behaviour for all requests via `MediaManager.setGlobalUploadPolicy()`. Controls maximum concurrent uploads, network requirements, retry limits, and backoff. Individual request policies override the global policy.
```java
// Allow up to 3 concurrent uploads, require WiFi, max 3 retries
GlobalUploadPolicy globalPolicy = new GlobalUploadPolicy.Builder()
.maxConcurrentRequests(3)
.networkPolicy(UploadPolicy.NetworkType.UNMETERED)
.maxRetries(3)
.backoffCriteria(30_000L, UploadPolicy.BackoffPolicy.EXPONENTIAL)
.build();
MediaManager.get().setGlobalUploadPolicy(globalPolicy);
// All subsequent uploads inherit this policy unless overridden per-request
MediaManager.get()
.upload(imageUri)
.unsigned("my_preset")
.dispatch(); // uses WiFi + 3 retries from global policy
```
```
--------------------------------
### Generate Facebook Profile Image URL
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Generate a URL for a Facebook profile image, applying transformations for a 130x130 fill crop with north-west gravity.
```java
MediaManager.get().url().type("facebook").transformation(new Transformation().width(130).height(130).crop("fill").gravity("north_west")).generate("billClinton.jpg")
```
--------------------------------
### Generate CDN URL for Uploaded Image
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Generates a CDN URL for an uploaded image using its public ID. This URL can be used to access the image immediately after a successful upload.
```java
MediaManager.get().url().generate("abcfrmo8zul1mafopawefg.jpg")
```
--------------------------------
### Maven Dependency for Cloudinary Android SDK
Source: https://github.com/cloudinary/cloudinary_android/blob/master/README.md
Add this dependency to your pom.xml for Maven integration.
```xml
com.cloudinary
cloudinary-android
3.1.2
```
--------------------------------
### Cancel Cloudinary Upload Requests
Source: https://context7.com/cloudinary/cloudinary_android/llms.txt
Cancel specific or all pending upload requests using their requestId or by calling a general cancellation method. Returns the number of cancelled requests.
```java
boolean cancelled = MediaManager.get().cancelRequest(requestId);
```
```java
int numCancelled = MediaManager.get().cancelAllRequests();
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.