O Drive and Photo Service SDK para Android permite fazer upload, baixe e gerencie arquivos por meio de uma interface nativa do Android. Versão mínima suportada: API 21.
Informações do SDK
|
Nome do SDK |
Drive and Photo Service SDK for Android |
|
Desenvolvedor |
Alibaba Cloud Computing Co., Ltd. |
|
Versão do SDK |
0.1.4 |
|
Nome do pacote do SDK |
com.aliyun.pds.sdk |
|
Data de atualização do SDK |
2023-07-19 |
|
Tamanho do SDK |
159,76 KB |
|
Hash MD5 do SDK |
47643c218b682f5c59ac2f17bb9044b4 |
|
Política de privacidade |
|
|
Baixe do SDK |
Integrar o SDK
Importe o SDK via Gradle.
implementation 'com.aliyun.pds:android-sdk:0.1.4'
Código-fonte: aliyun-pds-android-sdk.
A versão mínima suportada do Android SDK é a API 21.
Inicialização
Antes de usar o SDK, ative o Drive and Photo Service e crie uma instância no console. Para mais informações, consulte Primeiros passos com o PDS.
// Obtain the access token from your account system. Your backend uses the AppKey and AppSecret from the PDS platform to request a token and returns it to the client.
val token = SDToken("your access token")
// Get your API host from the PDS console.
val apiHost = "your API host"
val config = SDConfig.Builder(token, apiHost, 3600)
// Enable instant upload. Default: true. (Optional)
.canFastUpload()
// The User-Agent header for the request. (Optional)
.userAgent()
// The maximum number of retry attempts. Default: 3. (Optional)
.maxRetryCount()
// Specifies whether to enable debug mode. Default: false. (Optional)
.isDebug()
// Download chunk size. Default: 10 MB. Do not set this value too small or too large. (Optional)
.downloadBlockSize()
// Upload chunk size. Default: 4 MB. Do not set this value too small or too large. (Optional)
.uploadBlockSize()
// The timeout period for establishing a network connection. Default: 15s. (Optional)
.connectTimeout()
// The timeout period for reading a network response. Default: 60s. (Optional)
.readTimeout()
// The timeout period for writing a network request. Default: 60s. (Optional)
.writeTimeout()
.build()
SDClient.instance.init(this, config)
O SDK não atualiza o token de acesso automaticamente. Recupere periodicamente o token mais recente do servidor e atualize o SDK:
SDClient.instance.updateToken(token)
Upload e baixe de arquivos
Os callbacks de progresso e status da tarefa são executados em uma thread em segundo plano. Mude para a thread principal antes de atualizar a UI.
Baixar um arquivo
// Build the download request.
val downloadInfo = DownloadRequestInfo.Builder()
.downloadUrl(url)
.driveId(driveId)
.fileId(fileId)
.fileName(fileName)
.fileSize(fileSize)
// The path to save the file.
.filePath(dir.path)
// From a share: ID. Optional if the file is not from a share.
.shareId(shareId)
// From a share: token. Optional if the file is not from a share.
.shareToken(shareToken)
// From a share: password. Optional if the file is not from a share.
.sharePwd(sharePwd)
// For historical versions: ID. Required when downloading a historical version of a file. Optional otherwise.
.revisionId(revisionId)
// The hash value for verification.
.contentHash(hash)
// The hash verification algorithm. Currently, only crc64 is supported.
.contentHashName("crc64")
.build()
/*
* Create and start a task.
* If you specify the taskId of an incomplete task, the download resumes from where it left off.
* Do not specify the taskId of a completed task. This will immediately trigger the completion callback.
* Use a unique taskId for each new task. Reuse a taskId only to resume a task.
*/
val task = SDClient.instance.startDownloadTask(
taskId,
downloadInfo,
// The listener for download completion. Called on success or failure.
completeListener,
// The listener for download progress.
progressListener
)
/*
* By default, startDownloadTask starts the task.
* If a task is stopped, call this method to restart and continue it.
*/
task.start()
/*
* Stop the task. If the clean parameter is false, temporary files are not deleted, and calling start() resumes the task.
* If the clean parameter is true, temporary files and data are deleted, and calling start() restarts the task from the beginning.
*/
task.stop(clean)
Fazer upload de um arquivo
// Build the upload request.
val uploadInfo = UploadRequestInfo.Builder()
.fileName("edmDrive")
.filePath(file.absolutePath)
.fileSize(file.length())
.parentId(parentId)
.driveId(driveId)
.mimeType(mimeType)
// Specify the file ID. Required only when overwriting an existing file.
.fileId(fileId)
/*
* How to handle a file with a duplicate name. Default: "auto_rename".
* auto_rename: Appends a timestamp to the file name, for example, xxx_20060102_150405.
* ignore: Allows files with the same name to coexist.
* refuse: Rejects the new file and returns a success response if a file with the same name exists.
*/
.checkNameMode(checkNameMode)
// For shares. Optional if not related to a share.
.shareId(shareId)
.shareToken(shareToken)
.sharePwd(sharePwd)
.build()
// Create and start the task.
val task = SDClient.instance.startUploadTask(
taskId,
uploadInfo,
// The listener for upload completion. Called on success or failure.
completeListener,
// The listener for upload progress.
progressListener
)
/*
* By default, startUploadTask starts the task.
* If a task is stopped, call this method to restart and continue it.
*/
task.start()
/*
* Stop the task. If the clean parameter is false, temporary files are not deleted, and calling start() resumes the task.
* If the clean parameter is true, temporary files and data are deleted, and calling start() restarts the task from the beginning.
*/
task.stop(clean)
Callback de progresso da tarefa
// currentSize reports the number of bytes transferred. This callback runs on a background thread.
interface OnProgressListener {
fun onProgressChange(currentSize : Long)
}
Callback de conclusão da tarefa
interface OnCompleteListener {
fun onComplete(taskId: String, fileMeta : SDFileMeta, errorInfo: SDErrorInfo?)
}
O parâmetro fileMeta contém as informações do arquivo.
class SDFileMeta(
// The file ID.
val fileId: String?,
// The file name.
val fileName: String?,
// The file path. Upload: source file path. Download: save path.
val filePath: String?,
// The uploadId for the upload task (for internal use).
val uploadId: String? = ""
)
class SDErrorInfo(
// The error code.
val code: SDTransferError,
// The error description.
val message: String,
// The exception, used to view the stack trace for debugging.
val exception: Exception?,
// If a backend request error occurs, this value is returned for troubleshooting.
var requestId: String? = ""
)
Códigos de erro
SDTransferError.Unknown // Unknown error.
SDTransferError.Network // Network error.
SDTransferError.Server // Server error.
SDTransferError.FileNotExist // During upload, the local file was not found.
SDTransferError.SpaceNotEnough // During download, there is not enough local storage space.
SDTransferError.TmpFileNotExist // During download, the local temporary file does not exist.
SDTransferError.PathRuleError // During download, the save path rule is invalid.
A tarefa inicia automaticamente após a criação. Obtenha o progresso atual pelo callback de progresso. O listener de conclusão é chamado quando a tarefa tem sucesso ou falha.
Gerencie arquivos pela API
Para obter detalhes completos sobre os parâmetros de requisição e resposta, consulte a referência da API de Gerenciamento de arquivos.
Acesse as operações de arquivo por meio de SDClient.fileApi:
Os exemplos de requisição abaixo mostram apenas os parâmetros obrigatórios. Para parâmetros opcionais, consulte a referência da API.
Listar arquivos em uma pasta
fun fileList(fileListRequest: FileListRequest): FileListResp?
// For other FileListRequest parameters, see the FileListRequest implementation.
val request = FileListRequest()
// The fileId of the folder to list. Use "root" for the root directory.
request.parentId = "root"
// The driveId that contains the folder.
request.driveId = ""
Crie um arquivo ou pasta
// FileCreateRequest example.
val createRequest = FileCreateRequest()
// enum (ignore, auto_rename, refuse)
createRequest.checkNameMode = "auto_rename"
// The driveId where the file will be created.
createRequest.driveId = ""
// The name of the new file.
createRequest.name = ""
// The fileId of the parent directory. Use "root" for the root directory.
createRequest.parentFileId = "root"
// enum (file, folder)
createRequest.type = "folder"
Obter um arquivo ou pasta
// Get file or folder information.
fun fileGet(getResp: FileGetRequest): FileGetResp?
// FileGetRequest example.
val getRequest = FileGetRequest()
// The driveId of the file.
getRequest.driveId = ""
// The fileId.
getRequest.fileId = ""
Copiar um arquivo ou pasta
// Copy a file or folder.
fun fileCopy(fileCopyRequest: FileCopyRequest): FileCopyResp?
// FileCopyRequest example.
val copyRequest = FileCopyRequest()
// The driveId of the file.
copyRequest.driveId = ""
// The fileId.
copyRequest.fileId = ""
// The driveId of the destination folder.
copyRequest.toDriveId = ""
// The new name for the copied file.
copyRequest.newName = ""
// The fileId of the destination parent folder. Use "root" for the root directory.
copyRequest.toParentId = "root"
Mover um arquivo ou pasta
// Move a file or folder.
fun fileMove(fileMoveRequest: FileMoveRequest): FileMoveResp?
// FileMoveRequest example.
val moveRequest = FileMoveRequest()
// The driveId of the file.
moveRequest.driveId = ""
// The fileId.
moveRequest.fileId = ""
// The driveId of the destination folder.
moveRequest.toDriveId = ""
// The new name for the moved file.
moveRequest.newName = ""
// The fileId of the destination parent directory. Use "root" for the root directory.
moveRequest.toParentId = "root"
Renomear um arquivo ou pasta
fun fileUpdate(updateRequest: FileUpdateRequest): FileGetResp?
// FileUpdateRequest example.
val updateRequest = FileUpdateRequest()
// The driveId of the file.
updateRequest.driveId = item.driveId!!
// The fileId.
updateRequest.fileId = item.fileId
// The new name for the file or folder.
updateRequest.name = ""
Exclua um arquivo ou pasta
fun fileDelete(deleteRequest: FileDeleteRequest): FileDeleteResp?
// FileDeleteRequest example.
val delRequest = FileDeleteRequest()
// The driveId of the file.
delRequest.driveId = ""
// The fileId of the file or folder to delete.
delRequest.fileId = ""
Pesquisar arquivos
fun fileSearch(fileSearchRequest: FileSearchRequest): FileListResp?
// FileSearchRequest example.
// For query syntax, see https://www.alibabacloud.com/help/document_detail/175890.html
val request = FileSearchRequest()
// keyStr: The search keyword.
request.query = "name match '$keyStr' and status = 'available'"
request.driveId = ""
Outras operações
// Get the upload URL for file chunks.
fun fileGetUploadUrl(getUploadUrlRequest: FileGetUploadUrlRequest): FileGetUploadUrlResp?
// Mark a file upload as complete.
fun fileComplete(completeRequest: FileCompleteRequest): FileGetResp?
// Get a temporary download URL for a file.
fun fileGetDownloadUrl(getDownloadUrlRequest: FileGetDownloadUrlRequest): FileGetDownloadUrlResp?
// Query the status of an asynchronous task (for example, deleting a folder with multiple files).
fun getAsyncTask(getAsyncTaskRequest: AsyncTaskRequest): AsyncTaskResp?