Set up resumable uploads for Android
The FastPix Android Resumable Uploads SDK helps you efficiently upload large files from the browser by splitting them into chunks and also gives you the ability to pause and resume your uploads.
How resumable uploads work through chunking
Resumable uploads can be effectively handled through a technique called chunking. This method involves breaking down large files into smaller, more manageable pieces, or “chunks.” Here’s how chunking works:
- Divide the file: Large files are split into smaller, manageable chunks (e.g., 16 MB by default).
- Upload individually: Each chunk is uploaded separately. If a chunk fails, only that specific chunk needs to be re-uploaded.
- Resume capability: If the upload is interrupted, you can resume from the last successfully uploaded chunk instead of starting over.
This approach is important because:
- It reduces the risk: Uploading smaller chunks minimizes the risk of failure. If a chunk fails to upload due to network issues, only that specific chunk needs to be re-uploaded, not the entire file.
- Improves performance: Smaller chunks can be uploaded more quickly and efficiently, especially on slower connections, as they require less time to transfer.
- Easier management: Chunking allows for better tracking of upload progress, making it easier to implement features like pause and resume.
Step 1: Install the Android SDK
Add our repository to your Gradle project
Add the dependency to your app
Add Fastpix’s library to the dependencies block of your app in module level build.gradle file.
Step 2: Create an upload URL
In order to upload a video, you will need a signed upload URL.
To get this signed URL, you’ll need a valid Access Token and Secret Key. See the Authentication Guide for details on retrieving these credentials.
After obtaining your credentials, the next step is to generate a signed URL by calling the Upload Media from Device API. Once you have the signed URL, you’re all set to move forward with integrating the SDK into your app.
The example below demonstrates how to retrieve a signed URL using the Upload Media from Device API. You can either use this example directly or refer to our guide on uploading videos directly for more details.
PLEASE NOTE
When making Basic Auth API calls, securely retrieve the username and password from environment variables (.env) or a protected server endpoint to prevent unauthorized access.
In the API response, you will get a signed URL upon successful API request. Next step is to take the signed URL and pass it to the SDK.
Step 3: Start your upload
To perform the upload from your Android app, you can use the FastPixUploadSdk class. At the simplest, you need to build your FastPixUploadSdk via its Builder, then add your listeners and start() the upload.
Parameters to use:
This SDK supports the following parameters
Monitor the upload progress through lifecycle events
Using the following lifecycle events lets you to build a robust and user-friendly upload experience. By tracking progress in real-time, handling errors proactively, managing chunk retries, and responding to network changes, you can ensure seamless and efficient uploads.
Integrating these event handlers into your application can enhance reliability, optimize performance, and provide users with clear, actionable feedback throughout the upload process.
Manage video uploads
You can control the upload lifecycle with the following methods:
Pause an upload:
Resume an upload:
Abort an upload:
Usage example of Android uploads SDK
The following examples give an overview of integrating the FastPix Android Uploads SDK into your project, enabling you to build a fully customized upload interface. By making use of the SDK’s lifecycle events and configurable attributes, you can enhance functionality and optimize the upload experience.
Changelog
All notable changes to the Upload SDK for android will be documented below.
Current version
[2.0.0]
A full rewrite of the upload engine for spec-compliant, production-grade GCS resumable uploads. Breaking: the public API has changed — see the migration table in the README.
Added
- New public API under
io.fastpix.uploads:FastPixUploader(replacesFastPixUploadSdk) with a fluentBuilderandstart()/pause()/resume()/cancel()methods.UploadListener(replacesFastPixUploadCallbacks) with no-op defaults — override only what you need. New callbacks:onStateChange(UploadState),onPrepared(...),onChunkUploaded(...),onRetryScheduled(...),onCancelled(...).UploadStateenum (IDLE,PREPARING,UPLOADING,PAUSED,RETRYING,NETWORK_LOST,QUERYING_STATUS,COMPLETED,FAILED,CANCELLED) for explicit lifecycle modelling.UploadErrorsealed class with typed variants:InvalidConfiguration,FileNotFound,FileNotReadable,FileEmpty,FileReadFailure,NetworkFailure,SessionExpired(HTTP 410),ClientError(code),ServerError(code),RetryLimitExceeded,UnexpectedResponse.
- GCS spec compliance:
- Chunk PUTs with
Content-Range: bytes start-end/total; non-final chunk size enforced as a multiple of 256 KiB at build time. - Server-authoritative resume: parses the
Rangeheader from308 Resume Incompleteand resumes fromlast + 1. Handles 308 without aRangeheader (resume from byte 0) per spec. - Always issues a status query (
PUTwithContent-Range: bytes */TOTAL, empty body) before resuming after pause, network loss, or transient failure — never assumes how much the server has. - HTTP 410 →
UploadError.SessionExpired. Retryable: 408, 429, 5xx. Fatal: other 4xx.
- Chunk PUTs with
- Smooth, monotonic progress. Updates fire as each chunk streams (no longer only at chunk boundaries), throttled to one event per integer-percent change. A CAS-guarded high-water mark ensures progress never regresses on retry.
- Explicit upload state machine with validated transitions. Structurally impossible to send a chunk PUT after pause/retry/network-loss without first going through
QUERYING_STATUS. - Single-threaded engine. All state mutations serialised on one executor; OkHttp callbacks, network events, consumer commands, and retry timers all funnel through it. No race conditions.
- Multi-transport network awareness. Tracks the active set of networks with INTERNET capability; only signals offline when all transports drop. Transient WiFi/cellular handover events no longer trip false
NETWORK_LOST. - Configurable retry policy. Full-jitter exponential backoff (
retryBaseDelay,retryMaxDelay), bounded bymaxRetries. - Main-thread callback dispatch by default. Listener calls land on the main looper; consumers no longer need
runOnUiThreadwrappers. Override viaBuilder.callbackExecutor(Executor). - Optional HTTP logging via
Builder.debugLogging(true). Off by default — release builds no longer leak signed session URIs to logcat. - JUnit unit tests for
GcsResumableProtocol,UploadStateMachine,RetryPolicy, andCallbackDispatcher(47 tests total).
Fixed
- Retries no longer silently disabled after the first successful chunk. The retry executor is now permanent for the upload’s lifetime; previously a
CoroutineScope.cancel()killed it after chunk 1, causing later failures to hang forever. - Network failures are now routed through the retry path. Previously any
IOException(broken pipe, DNS hiccup, TLS reset, OkHttp cancel) terminated the upload withonError. Now classified, backed off, and resumed via status query. onSuccess,onFailure, andonCancellednow actually fire. A “defense in depth” terminated-flag silently dropped the terminal callback itself. Removed.cancel()no longer double-firesonError+onCancelled. OkHttp call cancellation is now correctly distinguished from real failures via a generation counter.pause()no longer leaks asonError. Intentional cancellations are detected inonFailureand suppressed.NetworkCallbackno longer leaks across uploads. Per-uploader registration with explicitunregisterNetworkCallbackon terminal.- Working Wi-Fi no longer falsely reported as
NETWORK_LOST. Dropped theNET_CAPABILITY_VALIDATEDrequirement, which is gated on a probe to Google’sconnectivitycheckendpoint and is missing for the first few seconds of a fresh connection (and indefinitely on networks where that endpoint is blocked, e.g. corporate Wi-Fi). - Transient losses during WiFi/cellular handover no longer trigger
NETWORK_LOST. Network state is now derived from the set of matching networks; offline is signalled only when all transports drop. - File reads no longer silently misalign on large files.
RandomAccessFile.seek()replacesInputStream.skip(), which was allowed to skip fewer bytes than requested. - OkHttp no longer silently re-PUTs bodies on connection failure.
retryOnConnectionFailure(false)lets the upload engine own all retry semantics. - Public commands after terminal state no longer crash.
cancel()called twice, late OkHttp callbacks, and late connectivity events post-teardown now silently no-op instead of throwingRejectedExecutionException.
Changed
- Minimum SDK bumped from API 21 to API 24.
- Default chunk size changed from 16 MiB to 8 MiB (the GCS-recommended value).
- Method renames (see migration table in README):
setSignedUrl→sessionUri,setFile→file,setChunkSize→chunkSize,setMaxRetries→maxRetries,setRetryDelay→retryBaseDelay+retryMaxDelay,callback→listener,startUpload→start,pauseUploading→pause,resumeUploading→resume,abort→cancel. - Errors:
UploadExceptionsand its subclasses replaced with theUploadErrorsealed hierarchy.
Removed
FastPixUploadSdk,FastPixUploadCallbacks,UploadExceptions,StreamingFileRequestBody,RetryHelper,NetworkHandler,UploadEventType.
Previous version
v1.0.1
- Implemented support for Google Cloud Storage resumable uploads and chunked client uploads.
- Added retry mechanism with exponential backoff for GCS upload failures based on retryable status codes.
- Enabled support for user-provided signed URLs, allowing resumable uploads to work with externally generated session URIs.
- Updated the API endpoint from https://v1.fastpix.io/on-demand/uploads to https://api.fastpix.com/v1/on-demand/upload for obtaining signed URLs.
v1.0.0
Features:
- Chunking: Files are automatically split into chunks (default chunk size is 16MB).
- Pause and Resume: Allows temporarily pausing the upload and resuming after a while.
- Retry: Uploads might fail due to temporary network failures. Individual chunks are retried for 5 times with exponential backoff to recover automatically from such failures.
- Lifecycle Event Listeners: Provides real-time feedback through various upload lifecycle events.
- Error Handling: Comprehensive error management to notify users of issues during uploads.
- Customizability: Options to customize chunk size and retry attempts.