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 |
build.gradle:dependencies {...// Add this lineimplementation 'com.qcloud.cos:cos-android:5.9.+'}
build.gradle:dependencies {...// Add this lineimplementation 'com.qcloud.cos:cos-android-lite:5.9.+'}
dependencies {...// Modify toimplementation 'com.qcloud.cos:cos-android-nobeacon:x.x.x'// Modify to lite versionimplementation 'com.qcloud.cos:cos-android-lite-nobeacon:x.x.x'}
/*** 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)
jar or aar packages. Below is a brief description of them. Please select the package to integrate based on your needs.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 lineimplementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])}
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"/>
AndroidManifest.xml under the application module:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
// Obtain temporary key (the way the business layer controls acquisition) String tmpSecretId = "SECRETID"; // Temporary key SecretIdString tmpSecretKey = "SECRETKEY"; // temporary key SecretKeyString sessionToken = "SESSIONTOKEN"; // temporary key Tokenlong 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 secondsSessionQCloudCredentials sessionQCloudCredentials = new SessionQCloudCredentials(tmpSecretId, tmpSecretKey,sessionToken, startTime, expiredTime);
// Implement aBasicLifecycleCredentialProvidersubclass to handle the process of requesting temporary keys and returning the results.public static class MySessionCredentialProviderextends BasicLifecycleCredentialProvider {@Overrideprotected 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 informationString tmpSecretId = "SECRETID"; // temporary key SecretIdString tmpSecretKey = "SECRETKEY"; // temporary key SecretKeyString sessionToken = "SESSIONTOKEN"; // temporary key Tokenlong 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 signaturelong startTime = 1556182000L; // valid start time of the temporary key, in seconds// Finally, return the temporary key information objectreturn new SessionQCloudCredentials(tmpSecretId, tmpSecretKey,sessionToken, startTime, expiredTime);}}
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*/@Overridepublic void sign(QCloudHttpRequest request) throws QCloudClientException {// 1. Pass the request parameters to the server to calculate the signatureString auth = "get auth from server";// 2. Add the signature to the requestrequest.addHeader(HttpConstants.Header.AUTHORIZATION, auth);}});
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=1String 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 secondsQCloudCredentialProvider 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);
// Bucket region abbreviation, for example, ap-guangzhou for GuangzhouString region = "COS_REGION";// Create a CosXmlServiceConfig object and modify the default configuration parameters as neededCosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder().setRegion(region).isHttps(true) // Use HTTPS requests. The default is HTTP requests..builder();
CosXmlService. CosXmlService provides all APIs for accessing COS and is recommended to be used as a singleton pattern.CosXmlService. You may skip setting the temporary key callback.CosXmlService cosXmlService = new CosXmlService(context,serviceConfig);
// Any CosXmlRequest supports this method, for example, upload PutObjectRequest, download GetObjectRequest, delete DeleteObjectRequest, etc.// The following uses upload as an examplePutObjectRequest 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 TransferManagerTransferManager transferManager = new TransferManager(cosXmlService, transferConfig);COSXMLUploadTask uploadTask = transferManager.upload(putRequest, null);
// Here, it is assumed that the class name isMySessionCredentialProvider. Initialize an instance to provide keys to the SDK.QCloudCredentialProvider myCredentialProvider = new MySessionCredentialProvider();CosXmlService cosXmlService = new CosXmlService(context,serviceConfig, myCredentialProvider);
CosXmlService cosXmlSelfService = new CosXmlService(context,serviceConfig, myQCloudSelfSigner);
CosXmlService cosXmlService = new CosXmlService(context,serviceConfig, myCredentialProvider);
{"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/*"]}]}
// 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 TransferManagerTransferManager 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/bucketString bucket = "examplebucket-1250000000";String cosPath = "exampleobject.txt"; // The location identifier of the object in the bucket, also known as the object keyString 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 nullString 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() {@Overridepublic void onSuccess(InitiateMultipartUpload initiateMultipartUpload) {// uploadId used for resuming the upload next timeString uploadId = initiateMultipartUpload.uploadId;}});// Set the upload progress callbackcosxmlUploadTask.setCosXmlProgressListener(new CosXmlProgressListener() {@Overridepublic void onProgress(long complete, long target) {// todo Do something to update progress...}});// Set the result callbackcosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {@Overridepublic 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?@Overridepublic 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 progresscosxmlUploadTask.setTransferStateListener(new TransferStateListener() {@Overridepublic void onStateChanged(TransferState state) {// todo notify transfer state}});
{"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/*"]}]}
// 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 TransferManagerTransferManager 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/bucketString bucket = "examplebucket-1250000000";String cosPath = "exampleobject.txt"; // The location identifier of the object in the bucket, also known as the object key//Local directory pathString 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// contextCOSXMLDownloadTask cosxmlDownloadTask =transferManager.download(applicationContext,bucket, cosPath, savePathDir, savedFileName);// Set the download progress callbackcosxmlDownloadTask.setCosXmlProgressListener(new CosXmlProgressListener() {@Overridepublic void onProgress(long complete, long target) {// todo Do something to update progress...}});// Set the result callbackcosxmlDownloadTask.setCosXmlResultListener(new CosXmlResultListener() {@Overridepublic 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?@Overridepublic 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 progresscosxmlDownloadTask.setTransferStateListener(new TransferStateListener() {@Overridepublic void onStateChanged(TransferState state) {// todo notify transfer state}});
Feedback