tencent cloud

Getting Started
Last updated:2026-03-04 15:00:04
Getting Started
Last updated: 2026-03-04 15:00:04

SDK Information

SDK Name
COS V5 Android SDK
Version number.
5.9.48
SDK provider's company name
Tencent Cloud Computing (Beijing) Limited Liability Company
Purpose of use and feature scenarios
The feature of data storage and management has been implemented, allowing users to upload, download, and manage files in any format.
SDK Download

Relevant Resources

To download the SDK source code, see COS V5 Android SDK.
For the example Demo, see COS V5 Android SDK Demo.
For SDK API and parameter documentation, please see SDK API Reference.
For all sample code in the SDK documentation, see SDK Code Samples.
See ChangeLog for the SDK change log.
For SDK FAQs, see Android SDK FAQs.
Note:
If you encounter errors such as functions or methods not existing when using the XML version SDK, please first upgrade the XML version SDK to the latest version and then retry.

Environment Configuration and Preparation

1. You need an Android app, which can be either your existing project or a new project you create.
2. Please ensure your Android app targets API level 15 (Ice Cream Sandwich) or higher.
3. You need a remote address that can obtain Tencent Cloud temporary credentials. For details about temporary credentials, see Mobile Application Direct Transfer Practice.

Installing the SDK

Method 1: Automatic Integration (Recommended)

COS SDK has three editions: Standard Edition, Lite Edition, and Without Tencent Beacon Edition.
Standard Edition: includes all features of the COS API and offers the most comprehensive functionality.
Lite Edition: only includes the file upload/download feature of COS (If you only require upload and download functionality and have strict requirements on SDK size, we recommend using the Lite Edition SDK).
Without Tencent Beacon Edition: removes Tencent's Beacon data reporting service based on the Standard Edition or Lite Edition.
Standard Edition SDK
Lite Edition SDK
Without Tencent Beacon Edition SDK
At the application level (usually under the App module), add dependencies in build.gradle:
dependencies {
...
// Add this line
implementation 'com.qcloud.cos:cos-android:5.9.+'
}
If you only require upload and download functionality and have strict requirements on SDK size, you can use our Lite Edition SDK.
At the application level (usually under the App module), add dependencies in build.gradle:
dependencies {
...
// Add this line
implementation 'com.qcloud.cos:cos-android-lite:5.9.+'
}
Note:
When using the Lite Edition SDK, please replace CosXmlService with CosXmlSimpleService in all sample codes.
In order to continuously track and optimize the quality of the SDK and provide you with a better user experience, we have introduced the Tencent Beacon SDK.
Note:
Tencent Beacon only monitors the request performance on the COS side and will not report business-side data.
If you want to disable this feature, you can perform operation 1 or 2:
1. Call the PrivacyService.closeReport() method to disable it (sdk version must be greater than or equal to 5.9.24).
2. Please perform the following operations in the build.gradle file at the application level (usually under the App module):
Version 5.8.0 and above:
Modify the dependencies of cos-android to.
dependencies {
...
// Modify to
implementation 'com.qcloud.cos:cos-android-nobeacon:x.x.x'

// Modify to lite version
implementation 'com.qcloud.cos:cos-android-lite-nobeacon:x.x.x'
}

Obtain the Personal Information Reported by Tencent Beacon

You can call the PrivacyService.getPrivacyParams(context) API to view the personal information reported by this sdk (the sdk version must be greater than or equal to 5.9.24).
/**
* Obtain possible collected parameters
* These parameters are used to analyze system operating status, optimize system performance and stability, and will not be used for other purposes.
* os_version: system version
* client_local_ip: local IP address
* network_type: network status
*/
public static Map<String, String> getPrivacyParams(Context context)

Method 2: Manual Integration

1. Download Archived Files

You can download the latest official package via the quick download link, or find all our historical versions of official packages in SDK Releases.
After downloading and extracting, you can see that it contains several jar or aar packages. Below is a brief description of them. Please select the package to integrate based on your needs.
Required libraries:
cos-android: COS protocol implementation
qcloud-foundation: foundation library
qcloud-cos-android-base: COS basic protocol implementation
qcloud-track: Log wrapper related
bolts-tasks: third-party Task library
okhttp: third-party Networking library
okio: third-party IO library

2. Integrating into the Project

Place the required packages in the libs directory under your application module, and add the following dependencies in the application-level (usually under the App module) build.gradle file:
dependencies {
...
// Add this line
implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
}

Configuring Permissions

Network Permissions

The SDK requires network permissions to communicate with the COS server. Add the following permission declaration in the AndroidManifest.xml under the application module:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Storage Permission

If your application scenario requires reading and writing files from external storage, add the following permission declaration in the AndroidManifest.xml under the application module:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Note:
On Android 6.0 (API level 23) and above, you need to dynamically request storage permissions at runtime.

Initialize COS Service

Note:
It is recommended that users use temporary keys to call the SDK, enhancing security through temporary authorization. When applying for temporary keys, follow the principle of least privilege to prevent leakage of resources other than the target bucket or objects.
If you must use permanent keys, it is recommended to follow the principle of least privilege to restrict the scope of permissions for the permanent keys.
For your business security, refer to Upload Security Restrictions for file uploads.

Set API Access Keys

Single-Use Temporary Key
Temporary Key Callback
Server-Side Signature Computation
Fixed Key (For Testing Only)
Set a single key to a specific CosXmlRequest (such as PutObjectRequest for uploads). This key is only used for this COS operation (such as uploads).
// Obtain temporary key (the way the business layer controls acquisition) String tmpSecretId = "SECRETID"; // Temporary key SecretId
String tmpSecretKey = "SECRETKEY"; // temporary key SecretKey
String sessionToken = "SESSIONTOKEN"; // temporary key Token
long expiredTime = 1556183496L;// expiration timestamp of the temporary key, in seconds
// It is recommended to return the server time as the start time of the signature to avoid requests expiring due to significant deviation in the user's local device time.
long startTime = 1556182000L; // valid start time of the temporary key, in seconds
SessionQCloudCredentials sessionQCloudCredentials = new SessionQCloudCredentials(tmpSecretId, tmpSecretKey,
sessionToken, startTime, expiredTime);
Note:
The COS Android SDK version must be greater than or equal to v5.9.31.
The COS SDK uses a callback approach to obtain temporary keys. The SDK will re-obtain temporary keys using this callback when the cached temporary keys are approaching expiration.
// Implement a BasicLifecycleCredentialProvider subclass to handle the process of requesting temporary keys and returning the results.
public static class MySessionCredentialProvider
extends BasicLifecycleCredentialProvider {

@Override
protected QCloudLifecycleCredentials fetchNewCredentials()
throws QCloudClientException {

// First, obtain the response containing key information from your temporary key server.

// Then parse the response to obtain the temporary key information
String tmpSecretId = "SECRETID"; // temporary key SecretId
String tmpSecretKey = "SECRETKEY"; // temporary key SecretKey
String sessionToken = "SESSIONTOKEN"; // temporary key Token
long expiredTime = 1556183496L;// expiration timestamp of the temporary key, in seconds

// It is recommended to return the server time as the start time of the signature to avoid requests expiring due to significant deviation in the user's local device time.
// Return the server time as the start time of the signature
long startTime = 1556182000L; // valid start time of the temporary key, in seconds

// Finally, return the temporary key information object
return new SessionQCloudCredentials(tmpSecretId, tmpSecretKey,
sessionToken, startTime, expiredTime);
}
}
Implement a subclass of QCloudSelfSigner to obtain the server-side signature and add it to the request authorization.
QCloudSelfSigner myQCloudSelfSigner = new QCloudSelfSigner() {
/**
* Sign the request
*
* @param request request to be signed
* @throws QCloudClientException client exception
*/
@Override
public void sign(QCloudHttpRequest request) throws QCloudClientException {
// 1. Pass the request parameters to the server to calculate the signature
String auth = "get auth from server";
// 2. Add the signature to the request
request.addHeader(HttpConstants.Header.AUTHORIZATION, auth);
}
});
You can use Tencent Cloud's permanent keys for local debugging during the development phase. Since this method poses the risk of key leakage, be sure to replace it with temporary keys before going live.
String secretId = "SECRETID"; // User's SecretId. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
String secretKey = "SECRETKEY"; // User's SecretKey. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1

// keyDuration is the validity period of the key in the request, in seconds
QCloudCredentialProvider myCredentialProvider =
new ShortTimeCredentialProvider(secretId, secretKey, 300);
// Starting from version 5.9.33, setting the start time is supported. If no start time is configured, the system current time will be used as the start time.
// Key validity start time in seconds. It is recommended to use the server time as the start time of the signature to avoid request expiration due to significant deviation in the user's local device time.
// long startTime = 1556182000L;
// QCloudCredentialProvider myCredentialProvider =
// new ShortTimeCredentialProvider(secretId, secretKey, startTime, 300);

Initialize COS

1. Configure the COS service through CosXmlServiceConfig.
// Bucket region abbreviation, for example, ap-guangzhou for Guangzhou
String region = "COS_REGION";

// Create a CosXmlServiceConfig object and modify the default configuration parameters as needed
CosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder()
.setRegion(region)
.isHttps(true) // Use HTTPS requests. The default is HTTP requests.
.builder();
Note:
For bucket region abbreviations, see Regions and Endpoints.
2. Initialize an instance of CosXmlService. CosXmlService provides all APIs for accessing COS and is recommended to be used as a singleton pattern.
Single-Use Temporary Key
Temporary Key Callback
Server-Side Signature Computation
Fixed Key (For Testing Only)
a. Initialize an instance of CosXmlService. You may skip setting the temporary key callback.
CosXmlService cosXmlService = new CosXmlService(context,serviceConfig);
b. Set a temporary key for CosXmlRequest and use it,
The temporary key for a single request takes precedence over the CredentialProvider initialized in CosXmlService. Therefore, the CredentialProvider configured in CosXmlService does not affect the setting of a single temporary key. Simply set the temporary key for CosXmlRequest using setCredential.
// Any CosXmlRequest supports this method, for example, upload PutObjectRequest, download GetObjectRequest, delete DeleteObjectRequest, etc.
// The following uses upload as an example
PutObjectRequest putRequest = new PutObjectRequest("examplebucket-1250000000", "exampleobject.txt", "local file path");
// sessionQCloudCredentials is the temporary key for a single request obtained in the first step "Initialize Key"
putRequest.setCredential(sessionQCloudCredentials);
// Initialize TransferConfig. The default configuration is used here. If customization is needed, see the SDK API documentation.
TransferConfig transferConfig = new TransferConfig.Builder().build();
// Initialize TransferManager
TransferManager transferManager = new TransferManager(cosXmlService, transferConfig);
COSXMLUploadTask uploadTask = transferManager.upload(putRequest, null);
Upload File Practice:
To upload files using a single temporary key, please refer to the Upload Object Practice Tutorial.
Note:
The COS Android SDK version must be greater than or equal to v5.9.31.
// Here, it is assumed that the class name is MySessionCredentialProvider. Initialize an instance to provide keys to the SDK.
QCloudCredentialProvider myCredentialProvider = new MySessionCredentialProvider();
CosXmlService cosXmlService = new CosXmlService(context,
serviceConfig, myCredentialProvider);
Initialize the COS Service through server-side signature authorization and obtain an instance.
CosXmlService cosXmlSelfService = new CosXmlService(context,
serviceConfig, myQCloudSelfSigner);
You can use Tencent Cloud's permanent keys for local debugging during the development phase. Since this method poses the risk of key leakage, be sure to replace it with temporary keys before going live.
CosXmlService cosXmlService = new CosXmlService(context,
serviceConfig, myCredentialProvider);

Access COS Service

PUT Object
Downloading an Object
Note:
For more complete examples, please visit GitHub.
After uploading, you can generate a file download URL using the same Key. For specific usage, refer to the Generate Pre-signed URL documentation. Note that if your file has private-read permission, the download URL will have a limited validity period.

Authorization Description

When configuring the Authorization Policy, see the following example for the action.
{
"version": "2.0",
"statement": [
{
"action": [
//head operation
"name/cos:HeadObject",
//Simple upload operation
"name/cos:PutObject",
//Multipart upload: Initializing multipart upload operations
"name/cos:InitiateMultipartUpload",
//Multipart upload: Listing ongoing multipart upload operations
"name/cos:ListMultipartUploads",
//Multipart upload: Listing uploaded parts
"name/cos:ListParts",
//Multipart upload: Uploading parts
"name/cos:UploadPart",
//Multipart upload: Completing all multipart upload operations
"name/cos:CompleteMultipartUpload",
//Canceling multipart upload operations
"name/cos:AbortMultipartUpload"
],
"effect": "allow",
"resource": [
"qcs::cos:ap-beijing:uid/1250000000:examplebucket-1250000000/doc/*"
]
}
]
}
For more actions in COS, see CAM-Supported Service Interfaces.
The SDK supports uploading local files, binary data, URIs, and input streams. The following example uses uploading local files:
Note:
During advanced upload, binary data and input streams only support simple upload and do not support multipart upload.
// Initialize TransferConfig. The default configuration is used here. If customization is needed, see the SDK API documentation.
TransferConfig transferConfig = new TransferConfig.Builder()
// Setting the minimum object size to enable multipart upload. Default: 2M
.setDivisionForUpload(2097152)
// Set the part size for multipart upload. Default: 1M
.setSliceSizeForUpload(1048576)
// Set whether to force the use of simple upload and disable multipart upload
.setForceSimpleUpload(false)
.build();
// Initialize TransferManager
TransferManager transferManager = new TransferManager(cosXmlService,
transferConfig);

// The bucket name consists of bucketname-appid, where the appid must be included. You can view the bucket name in the COS console. https://console.tencentcloud.com/cos5/bucket
String bucket = "examplebucket-1250000000";
String cosPath = "exampleobject.txt"; // The location identifier of the object in the bucket, also known as the object key
String srcPath = new File(context.getCacheDir(), "exampleobject.txt")
.toString(); // Absolute path of the local file
// If there is an UploadId for initializing multipart upload, assign the corresponding uploadId value for resuming; otherwise, assign null
String uploadId = null;

// Upload documents.
COSXMLUploadTask cosxmlUploadTask = transferManager.upload(bucket, cosPath,
srcPath, uploadId);

// Set the callback for initializing multipart upload to obtain the uploadId (supported in version 5.9.7 and later)
cosxmlUploadTask.setInitMultipleUploadListener(new InitMultipleUploadListener() {
@Override
public void onSuccess(InitiateMultipartUpload initiateMultipartUpload) {
// uploadId used for resuming the upload next time
String uploadId = initiateMultipartUpload.uploadId;
}
});
// Set the upload progress callback
cosxmlUploadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
@Override
public void onProgress(long complete, long target) {
// todo Do something to update progress...
}
});
// Set the result callback
cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
@Override
public void onSuccess(CosXmlRequest request, CosXmlResult result) {
COSXMLUploadTask.COSXMLUploadTaskResult uploadResult =
(COSXMLUploadTask.COSXMLUploadTaskResult) result;
}

// If you are using the kotlin language to make the call, note that exceptions in the callback method are nullable; otherwise, the onFail method will not be called back. Specifically:
// The type of clientException is CosXmlClientException?, and the type of serviceException is CosXmlServiceException?
@Override
public void onFail(CosXmlRequest request,
@Nullable CosXmlClientException clientException,
@Nullable CosXmlServiceException serviceException) {
if (clientException != null) {
clientException.printStackTrace();
} else {
serviceException.printStackTrace();
}
}
});
// Set the task status callback to monitor the task progress
cosxmlUploadTask.setTransferStateListener(new TransferStateListener() {
@Override
public void onStateChanged(TransferState state) {
// todo notify transfer state
}
});
Note:
For more complete examples, please visit GitHub.
The advanced download API supports resuming interrupted transfers, so it initiates a HEAD request to obtain file information before downloading. If you are using temporary keys or accessing with a sub-account, please ensure that the HeadObject permission is included in the permission list.

Description

When configuring the Authorization Policy, see the following example for the action.
{
"version": "2.0",
"statement": [
{
"action": [
//head operation
"name/cos:HeadObject",
//Downloading operation
"name/cos:GetObject",
],
"effect": "allow",
"resource": [
"qcs::cos:ap-beijing:uid/1250000000:examplebucket-1250000000/doc/*"
]
}
]
}
For more actions in COS, see CAM-Supported Service Interfaces.
// The advanced download API supports resuming interrupted transfers, so it initiates a HEAD request to obtain file information before downloading.
// If you are using temporary keys or accessing with a sub-account, please ensure that the HeadObject permission is included in the permission list.

// Initialize TransferConfig. The default configuration is used here. If customization is needed, see the SDK API documentation.
TransferConfig transferConfig = new TransferConfig.Builder().build();
//Initialize TransferManager
TransferManager transferManager = new TransferManager(cosXmlService,
transferConfig);

// The bucket name consists of bucketname-appid, where the appid must be included. You can view the bucket name in the COS console. https://console.tencentcloud.com/cos5/bucket
String bucket = "examplebucket-1250000000";
String cosPath = "exampleobject.txt"; // The location identifier of the object in the bucket, also known as the object key
//Local directory path
String savePathDir = context.getExternalCacheDir().toString();
// The filename saved locally. If not specified (null), it will be the same as the filename on COS.
String savedFileName = "exampleobject.txt";

Context applicationContext = context.getApplicationContext(); // application
// context
COSXMLDownloadTask cosxmlDownloadTask =
transferManager.download(applicationContext,
bucket, cosPath, savePathDir, savedFileName);

// Set the download progress callback
cosxmlDownloadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
@Override
public void onProgress(long complete, long target) {
// todo Do something to update progress...
}
});
// Set the result callback
cosxmlDownloadTask.setCosXmlResultListener(new CosXmlResultListener() {
@Override
public void onSuccess(CosXmlRequest request, CosXmlResult result) {
COSXMLDownloadTask.COSXMLDownloadTaskResult downloadTaskResult =
(COSXMLDownloadTask.COSXMLDownloadTaskResult) result;
}

// If you are using the kotlin language to make the call, note that exceptions in the callback method are nullable; otherwise, the onFail method will not be called back. Specifically:
// The type of clientException is CosXmlClientException?, and the type of serviceException is CosXmlServiceException?
@Override
public void onFail(CosXmlRequest request,
@Nullable CosXmlClientException clientException,
@Nullable CosXmlServiceException serviceException) {
if (clientException != null) {
clientException.printStackTrace();
} else {
serviceException.printStackTrace();
}
}
});
// Set the task status callback to monitor the task progress
cosxmlDownloadTask.setTransferStateListener(new TransferStateListener() {
@Override
public void onStateChanged(TransferState state) {
// todo notify transfer state
}
});

FAQs

You may encounter some common issues during usage. For related solutions, refer to Android SDK FAQs.
Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback