Resources
Download the XML Android SDK source code here. Note:
If you encounter errors such as non-existent functions or methods when using the XML version of the SDK, please update the SDK to the latest version and try again.
Preparations
1. You need an Android app, which can be one of your existing projects or a new one.
2. Make sure that your Android app’s target API level is 15 (Ice Cream Sandwich) or above.
3. You need a remote address where users can obtain your Tencent Cloud temporary key. For more information on temporary keys, see Direct Upload for Mobile Apps. Step 1. Install the SDK
Method 1. Automatic integration (recommended)
Note:
As the Bintray repository is no longer available, COS’s SDK has been migrated to Maven Central. The import path is different and thus you need to use the new import path during the update.
Using the Maven Central repository
Add the following code to the project-level build.gradle
file (usually in the root directory):
repositories {
google()
// Add the following line
mavenCentral()
}
Standard SDK
Add dependencies to the app-level build.gradle
file (usually under the App module).
dependencies {
...
// Add the following line
implementation 'com.qcloud.cos:cos-android:5.9.+'
}
Simplified SDK
Add dependencies to the app-level build.gradle
file (usually under the App module).
dependencies {
...
// Add the following line
implementation 'com.qcloud.cos:cos-android-lite:5.9.+'
}
Disabling beacon reporting
We have introduced the Tencent Beacon into the SDK to track down and optimize the SDK quality for a better user experience. Note:
DataInsight only monitors the COS request performance and doesn't report any business data.
To disable this feature, perform the following operations in the app-level build.gradle
file (usually under the App module):
For v5.8.0 or later:
Change the dependency of cos-android
to
dependencies {
...
// Change to
implementation 'com.qcloud.cos:cos-android-nobeacon:x.x.x'
//For lite version, change to
implementation 'com.qcloud.cos:cos-android-lite-nobeacon:x.x.x'
}
For v5.5.8–5.7.9:
Add the beacon removing statement
dependencies {
...
implementation ('com.qcloud.cos:cos-android:x.x.x'){
// Add the following line
exclude group: 'com.tencent.qcloud', module: 'beacon-android-release'
}
}
Method 2: Manually integrate
1. Download the SDK version
You can directly download the latest SDK version here or find all versions at SDK Releases. After downloading and decompressing the file, you can see that it contains multiple JAR
or AAR
packages as described below. Please choose the ones you want to integrate.
Required libraries:
cos-android: COS protocol implementation
qcloud-foundation: foundation library
okhttp: third-party networking library okio: third-party I/O library Optional libraries:
quic: QUIC protocol, required if you transfer data over QUIC
beacon: mobile beacon analysis to improve the SDK
2. Integrate the SDK into your project
Put your libraries in the app-module libs
folder and add dependencies to the app-level build.gradle
file (usually under the App module):
dependencies {
...
// Add the following line
implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
}
Network permissions
The SDK needs network permission to communicate with the COS server. Please add the following permission declarations to AndroidManifest.xml
under the app 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 permissions
If you need to read and write files from external storage, please add the following permission declarations to AndroidManifest.xml
under the app module:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Note:
For Android 6.0 (API level 23) or above, you need to dynamically request storage permissions at runtime.
Step 3. Use the SDK
1. Obtain a temporary key
Implement a BasicLifecycleCredentialProvider
subclass to request a temporary key and return the result.
public static class MySessionCredentialProvider
extends BasicLifecycleCredentialProvider {
@Override
protected QCloudLifecycleCredentials fetchNewCredentials()
throws QCloudClientException {
String tmpSecretId = "SECRETID";
String tmpSecretKey = "SECRETKEY";
String sessionToken = "SESSIONTOKEN";
long expiredTime = 1556183496L;
long startTime = 1556182000L;
return new SessionQCloudCredentials(tmpSecretId, tmpSecretKey,
sessionToken, startTime, expiredTime);
}
}
The following takes MySessionCredentialProvider
as the class name example to initialize an instance to provide a key for the SDK.
QCloudCredentialProvider myCredentialProvider = new MySessionCredentialProvider();
Using a permanent key for local debugging
You can use your Tencent Cloud permanent key for local debugging during the development phase. Since this method exposes the key to leakage risks, please be sure to replace it with a temporary key before launching your application.
String secretId = "SECRETID";
String secretKey = "SECRETKEY";
QCloudCredentialProvider myCredentialProvider =
new ShortTimeCredentialProvider(secretId, secretKey, 300);
Using the server-calculated signature to authorize the request
Implement a subclass of QCloudSelfSigner
to get the server-side signature and add it to the request authorization.
QCloudSelfSigner myQCloudSelfSigner = new QCloudSelfSigner() {
@Override
public void sign(QCloudHttpRequest request) throws QCloudClientException {
String auth = "get auth from server";
request.addHeader(HttpConstants.Header.AUTHORIZATION, auth);
}
});
2. Initialize a COS instance
Use your myCredentialProvider
instance that provides the key or the server-side signed and authorized instance myQCloudSelfSigner
to initialize a CosXmlService
instance.
CosXmlService
provides all APIs for accessing COS. We recommend you use it as an application singleton.
String region = "COS_REGION";
CosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder()
.setRegion(region)
.isHttps(true)
.builder();
CosXmlService cosXmlService = new CosXmlService(context,
serviceConfig, myCredentialProvider);
CosXmlService cosXmlService = new CosXmlService(context,
serviceConfig, myQCloudSelfSigner);
Step 4. Access COS
Uploading an object
The SDK supports uploading local files, binary data, URIs, and input streams. The following uses uploading a local file as an example:
TransferConfig transferConfig = new TransferConfig.Builder().build();
TransferManager transferManager = new TransferManager(cosXmlService,
transferConfig);
String bucket = "examplebucket-1250000000";
String cosPath = "exampleobject";
String srcPath = new File(context.getCacheDir(), "exampleobject")
.toString();
String uploadId = null;
COSXMLUploadTask cosxmlUploadTask = transferManager.upload(bucket, cosPath,
srcPath, uploadId);
cosxmlUploadTask.setInitMultipleUploadListener(new InitMultipleUploadListener() {
@Override
public void onSuccess(InitiateMultipartUpload initiateMultipartUpload) {
String uploadId = initiateMultipartUpload.uploadId;
}
});
cosxmlUploadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
@Override
public void onProgress(long complete, long target) {
}
});
cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
@Override
public void onSuccess(CosXmlRequest request, CosXmlResult result) {
COSXMLUploadTask.COSXMLUploadTaskResult uploadResult =
(COSXMLUploadTask.COSXMLUploadTaskResult) result;
}
@Override
public void onFail(CosXmlRequest request,
@Nullable CosXmlClientException clientException,
@Nullable CosXmlServiceException serviceException) {
if (clientException != null) {
clientException.printStackTrace();
} else{
serviceException.printStackTrace();
}
}
});
cosxmlUploadTask.setTransferStateListener(new TransferStateListener() {
@Override
public void onStateChanged(TransferState state) {
}
});
Note:
For the complete sample, please visit GitHub. After the upload, you can generate a download URL for the uploaded file with the same key. For detailed directions, see Generating Pre-signed Links. Please note that for private-read files, the download URL is only valid for a limited period of time. Downloading an object
TransferConfig transferConfig = new TransferConfig.Builder().build();
TransferManager transferManager = new TransferManager(cosXmlService,
transferConfig);
String bucket = "examplebucket-1250000000";
String cosPath = "exampleobject";
String savePathDir = context.getExternalCacheDir().toString();
String savedFileName = "exampleobject";
Context applicationContext = context.getApplicationContext();
COSXMLDownloadTask cosxmlDownloadTask =
transferManager.download(applicationContext,
bucket, cosPath, savePathDir, savedFileName);
cosxmlDownloadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
@Override
public void onProgress(long complete, long target) {
}
});
cosxmlDownloadTask.setCosXmlResultListener(new CosXmlResultListener() {
@Override
public void onSuccess(CosXmlRequest request, CosXmlResult result) {
COSXMLDownloadTask.COSXMLDownloadTaskResult downloadTaskResult =
(COSXMLDownloadTask.COSXMLDownloadTaskResult) result;
}
@Override
public void onFail(CosXmlRequest request,
@Nullable CosXmlClientException clientException,
@Nullable CosXmlServiceException serviceException) {
if (clientException != null) {
clientException.printStackTrace();
} else{
serviceException.printStackTrace();
}
}
});
cosxmlDownloadTask.setTransferStateListener(new TransferStateListener() {
@Override
public void onStateChanged(TransferState state) {
}
});
Note:
For the complete sample, please visit GitHub. The advanced download API supports checkpoint restart. Therefore, a HEAD request will be sent before the download to obtain the file information. If you are using a temporary key or accessing with a sub-account, ensure that your permission list includes HeadObject
.
Was this page helpful?