获取鉴权信息成功后,开发者必须先检查用户安全策略是否需要更新,具体参见“获取用户信息”操作。
本章节主要介绍接入华为云空间服务的开发步骤,以帮助开发者快速了解华为云空间服务提供的客户端接口及其调用方法。请开发者基于应用自身的使用场景,自行选择相应的开发章节。
Drive SDK提供的主要能力以及调用方法如下:
华为帐号是用户访问并使用个人云端文件的凭证,因此在使用Drive SDK时,需要先引导用户登录华为帐号。在登录成功后,将用户相关信息保存,在调用Drive SDK相关接口时使用。
基本流程如下:

如上所述,使用Drive SDK时,应用需要先通过HMS SDK获取用户信息,详见集成Drive SDK和HMS SDK。
通过HMS SDK登录时,需要通过HMS的HuaweiIdAuthParamsHelper.setScopeList接口设置Drive Scope,用于获取访问Drive接口的权限:
- List<Scope> scopeList = new ArrayList<>();
- scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE)); //所有权限,除了应用文件夹权限
- scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_READONLY)); // 只允许查看文件内容和元数据
- scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_FILE)); //允许查看和管理文件
- scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_METADATA)); //允许查看和管理文件元数据,但不包括文件实体
- scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_METADATA_READONLY)); //只允许查看文件元数据,但不包括文件实体
- scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_APPDATA)); //支持APP数据上传和存储
- scopeList.add(HuaweiIdAuthAPIManager.HUAWEIID_BASE_SCOPE); // 账号基本权限
- HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(DEFAULT_AUTH_REQUEST_PARAM)
- .setAccessToken()
- .setIdToken()
- .setScopeList(scopeList)
- .createParams();
不同的DriveScope对应不同的权限, 第三方开发者可以根据自己的业务需要申请对应权限。具体登录流程请参考《华为帐号服务开发指南》。
获取用户信息后,将用户的unionId和AccessToken(即at)保存,后续调用Drive SDK相关使用。如下示例描述了一种实现方法,开发者也可自行实现。
示例代码:
创建CredentialManager类:
- /**
- * Credential管理类
- * <p>
- * since 1.0
- */
- public class CredentialManager {
- /**
- * Drive鉴权信息
- */
- private DriveCredential mCredential;
- private CredentialManager() {
- }
- private static class InnerHolder {
- private static CredentialManager sInstance = new CredentialManager();
- }
- /**
- * 单例CredentialManager instance。
- *
- * @return CredentialManager
- */
- public static CredentialManager getInstance() {
- return InnerHolder.sInstance;
- }
- /**
- * 通过上下文context和华为账号信息(unionId,countrycode,accessToken)初始化drive。
- * 当accessToken失效时,注册一个AccessMethod去获取一个新的accessToken,传入的refreshAT不为null。
- *
- * @param unionID HwID中的unionID
- * @param at access token
- * @param refreshAT 刷新AT的回调函数,不能传入null
- */
- public int init(String unionID, String at, DriveCredential.AccessMethod refreshAT) {
- if (StringUtils.isNullOrEmpty(unionID) || StringUtils.isNullOrEmpty(at)) {
- return DriveCode.ERROR;
- }
- DriveCredential.Builder builder = new DriveCredential.Builder(unionID, refreshAT);
- mCredential = builder.build().setAccessToken(at);
- return DriveCode.SUCCESS;
- }
- /**
- * 获取DriveCredential
- *
- * @return DriveCredential
- */
- public DriveCredential getCredential() {
- return mCredential;
- }
- /**
- * 退出Drive,清理Drive使用过程中所有的缓存信息
- */
- public void exit(Context context) {
- // 清理缓存文件
- deleteFile(context.getCacheDir());
- deleteFile(context.getFilesDir());
- }
- /**
- * 删除缓存文件
- *
- * @param file 指定的缓存文件
- */
- private static void deleteFile(java.io.File file) {
- if (null == file || !file.exists()) {
- return;
- }
- if (file.isDirectory()) {
- java.io.File[] files = file.listFiles();
- if (files != null) {
- for (java.io.File f : files) {
- deleteFile(f);
- }
- }
- }
- }
- }
在登录成功onActivityResult回调中调用initDrive。
- private static DriveCredential.AccessMethod refreshAT = new DriveCredential.AccessMethod() {
- @Override
- public String refreshToken() {
- // 重新通过HMS获取accessToken
- return refreshAccessToken();
- }
- };
- private void initDrive() {
- // signInHuaweiId为登录HMS后获取到的用户帐号信息,通过signInHuaweiId获取unionId及accessToken
- final String unionID = signInHuaweiId.getUnionId();
- final String accessToken = signInHuaweiId.getAccessToken();
- int returnCode = CredentialManager.getInstance().init(unionID, accessToken, refreshAT);
- if (DriveCode.SUCCESS == returnCode) {
- // 初始化成功后跳转到应用主页面
- jumpToMainActivity();
- }
- }
获取鉴权信息成功后,开发者必须先检查用户安全策略是否需要更新,具体参见“获取用户信息”操作。
第三方应用可以通过About.get接口获取到用户华为云空间信息,例如空间容量大小,允许上传的最大文件大小等。
步骤1 调用Drive.Builder.build接口创建Drive对象。
- private Drive buildDrive() {
- Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
- return service;
- }
步骤2 调用About.get接口获取用户信息,设置字段setFields("*")表示返回所有字段。
- private About getAbout() {
- About response = null;
- try {
- Drive drive = buildDrive();
- Drive.About about = drive.about();
- response = about.get().setFields("*").execute();
- String res = response.toString();
- } catch (Exception e) {
- Log.e(TAG, "getInfo error: " + e.toString());
- }
- return response;
- }
步骤3 如果About.get接口返回响应中needUpdate字段值为true,表示需要用户更新安全策略,开发者需要根据返回的地址,跳转到授权页面,用户同意后可继续使用业务。
- /**
- * 判断是否要提示用户更新协议
- *
- * @param about 返回的About响应
- */
- private void checkUpdateProtocol(About about) {
- if (about == null) {
- return;
- }
- Log.d(TAG, "checkUpdate: " + about.toString());
- Object updateValue = about.get("needUpdate");
- boolean isNeedUpdate = false;
- if (updateValue instanceof Boolean) {
- isNeedUpdate = (Boolean) updateValue;
- }
- if (!isNeedUpdate) {
- return;
- }
- Object urlValue = about.get("updateUrl");
- String url = "";
- if (urlValue instanceof String) {
- url = (String) urlValue;
- }
- if (TextUtils.isEmpty(url)) {
- return;
- }
- Uri uri = Uri.parse(url);
- if (!"https".equals(uri.getScheme())) {
- return;
- }
- Intent intent = new Intent(Intent.ACTION_VIEW, uri);
- try {
- startActivity(intent);
- } catch (ActivityNotFoundException e) {
- Logger.e(TAG, "Activity Not found");
- }
- }
华为云空间服务的核心能力是对云端文件的管理,用户可以通过华为云空间服务方便快捷的管理、编辑华为云盘上的文件,支持创建、获取文件列表、拷贝、修改文件、移入回收站、清空回收站文件及搜索云盘上的文件等能力。
步骤1 调用Drive.Builder.build接口创建Drive对象。
- private Drive buildDrive() {
- Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
- return service;
- }
步骤2 调用Files接口能力。
示例代码中使用的常量:
private static final int DIRECT_UPLOAD_MAX_SIZE = 20 * 1024 * 1024;
private static final int DIRECT_DOWNLOAD_MAX_SIZE = 20 * 1024 * 1024;
调用Files.create接口创建目录:
- /**
- * 创建目录
- */
- private File createDirectory() {
- File directory = null;
- try {
- Drive drive = buildDrive();
- Map<String, String> appProperties = new HashMap<>();
- appProperties.put("appProperties", "property");
- SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
- String dirName = formatter.format(new Date());
- File file = new File();
- file.setFileName(dirName)
- .setAppSettings(appProperties)
- .setMimeType("application/vnd.huawei-apps.folder");
- directory = drive.files().create(file).execute();
- } catch (Exception e) {
- Logger.e(TAG, "createDirectory error: " + e.toString());
- }
- return directory;
- }
调用Files.create接口创建文件:
文件上传方式分为直接上传和断点续传两种,其中直接上传支持的最大文件大小为20M,推荐低于5M的文件通过直接上传的方式上传,而断点续传不限制文件大小,推荐超过5M的文件使用断点续传的方式上传。
方式一:直接上传文件。
- /**
- * 上传文件,该方式支持上传进度保存功能
- * (用户上传过程中断网等,下次再上传同一个文件时会接着上次的进度上传)
- *
- * @param filePath 文件路径
- * @param parentId 文件所在目录ID
- * @param thumbnailImageBuffer 缩略图数据
- * @param thumbnailMimeType 缩略图文件类型
- */
- private void createFile(String filePath, String parentId, byte[] thumbnailImageBuffer, String thumbnailMimeType) {
- try {
- if (filePath == null) {
- Logger.e(TAG, "createFile error, filePath is null.");
- return;
- }
- java.io.File file = new java.io.File(filePath);
- FileContent fileContent = new FileContent(null, file);
- // 设置缩略图数据
- File.ContentExtras contentExtras = new File.ContentExtras();
- File.ContentExtras.Thumbnail thumbnail = new File.ContentExtras.Thumbnail();
- thumbnail.setContent(Base64.encodeBase64String(thumbnailImageBuffer));
- thumbnail.setMimeType(thumbnailMimeType);
- contentExtras.setThumbnail(thumbnail);
- File content = new File()
- .setFileName(file.getName())
- .setParentFolder(Collections.singletonList(parentId))
- .setContentExtras(contentExtras);
- Drive drive = buildDrive();
- Drive.Files.Create request = drive.files().create(content, fileContent);
- boolean isDirectUpload = false;
- // 文件小于20M时可以使用直接上传
- if (file.length() < DIRECT_UPLOAD_MAX_SIZE) {
- isDirectUpload = true;
- }
- // 设置上传方式,默认使用断点续传。当文件小于20M时可以使用直接上传,即设置为true。
- request.getMediaHttpUploader().setDirectUploadEnabled(isDirectUpload);
- request.execute();
- } catch (Exception e) {
- Logger.e(TAG, "createFile exception: " + filePath + e.toString());
- }
- }
方式二:通过媒体流创建文件。
- /**
- * 通过InputStream创建文件
- *
- * @param inputStream 媒体流
- * @param parentId 文件所在目录ID
- * @param mimeType MIME类型,如image/jpeg、video/mp4等
- * @param inputStreamLength stream流长度
- */
- private void createFile(InputStream inputStream, String parentId, String mimeType, int inputStreamLength) {
- try {
- InputStreamContent streamContent = new InputStreamContent(mimeType, inputStream);
- streamContent.setLength(inputStreamLength);
- File content = new File()
- .setFileName("video.mp4")
- .setParentFolder(Collections.singletonList(parentId));
- Drive drive = buildDrive();
- drive.files().create(content, streamContent).execute();
- } catch (Exception e) {
- Logger.e(TAG, "createFile exception: " + e.toString());
- }
- }
调用Files.copy接口拷贝文件:
- /**
- * 拷贝文件到指定目录
- *
- * @param file 待拷贝的文件
- * @param dstDir 拷贝文件到指定的目录
- */
- private void copyFile(File file, ArrayList<String> dstDir) {
- try {
- File copyFile = new File();
- if (file == null || file.getFileName() == null ||dstDir == null) {
- Log.e(TAG, "copyFile arguments error");
- sendHandleMessage(R.id.drive_files_button_copy, FAIL);
- return;
- }
- SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
- String suffix = formatter.format(new Date());
- copyFile.setFileName(file.getFileName() + "_copy" + "_" + suffix);
- copyFile.setDescription("copyFile");
- copyFile.setParentFolder(dstDir);
- copyFile.setFavorite(true);
- copyFile.setEditedTime(new DateTime(System.currentTimeMillis()));
- Drive drive = buildDrive();
- Drive.Files.Copy copyFileReq = drive.files().copy(file.getId(), copyFile);
- copyFileReq.setFields("*");
- File result = copyFileReq.execute();
- } catch (IOException ex) {
- Log.e(TAG, "copyFile error: " + ex.toString());
- }
- }
调用Files.update接口修改文件(目录)的元数据:
- /**
- * 修改文件(目录),通过MIMEType区分是文件还是目录
- *
- * @param file 待修改的文件(目录)
- */
- private void updateFile(File file) {
- try {
- if (file == null) {
- Logger.e(TAG, "updateFile error, need to create file.");
- return;
- }
- Drive drive = buildDrive();
- File updateFile = new File();
- updateFile.setFileName(file.getFileName() +"_update")
- .setMimeType("application/vnd.huawei-apps.folder")
- .setDescription("update folder")
- .setFavorite(true);
- drive.files().update(file.getId(), updateFile).execute();
- } catch (Exception e) {
- Logger.e(TAG, "updateFile error: " + e.toString());
- }
- }
调用Files.update接口修改文件的元数据或内容:
- /**
- * 修改文件
- *
- * @param oldFile 源文件
- * @param newFilePath 更新后文件路径
- */
- private void updateFile(File oldFile, String newFilePath) {
- try {
- if (oldFile == null || TextUtils.isEmpty(newFilePath)) {
- Logger.e(TAG, "updateFile error, need to create file.");
- return;
- }
- java.io.File sourceFile = new java.io.File(newFilePath);
- FileContent fileContent = new FileContent(null, sourceFile);
- File updateFile = new File();
- updateFile.setFileName(oldFile.getFileName() + "_update")
- .setDescription("update folder")
- .setFavorite(true);
- Drive drive = buildDrive();
- Drive.Files.Update update = drive.files().update(oldFile.getId(), updateFile, fileContent);
- boolean isDirectUpload = false;
- // 文件小于20M时可以使用直接上传
- if (sourceFile.length() < DIRECT_UPLOAD_MAX_SIZE) {
- isDirectUpload = true;
- }
- // 设置上传方式,默认使用断点续传。当文件小于20M时可以使用直接上传,即设置为true。
- update.getMediaHttpUploader().setDirectUploadEnabled(isDirectUpload);
- update.execute();
- } catch (Exception e) {
- Logger.e(TAG, "updateFile error: " + e.toString());
- }
- }
调用Files.delete接口永久删除文件(或者目录):
- /**
- * 永久删除文件(目录)
- *
- * @param file 待删除的文件或目录
- */
- private void deleteFile(File file) {
- try {
- Drive drive = buildDrive();
- Drive.Files.Delete deleteFile = drive.files().delete(file.getId());
- deleteFile.execute();
- } catch (IOException ex) {
- Log.e(TAG, "deleteFile error: " + ex.toString());
- }
- }
调用Files.get接口获取文件元数据:
- /**
- *获取文件元数据
- *
- * @param fileId 文件Id
- */
- private File getFileMetadata(String fileId) {
- File file = null;
- try {
- Drive drive = buildDrive();
- Drive.Files.Get request = drive.files().get(fileId);
- request.setFields("*");
- file = request.execute();
- } catch (Exception e) {
- Logger.e(TAG, "get metadata error: " + e.toString());
- }
- return file;
- }
调用Files.get接口下载元数据及实体文件:
文件下载不限制文件大小。针对小文件(小于20M)可以通过设置参数directDownloadEnabled的值为true,通过一个网络请求,简单下载文件。
- /**
- * 下载文件元数据及文件实体
- *
- * @param fileId 文件Id
- * @param destFile 目标文件
- */
- private void downLoadFile(String fileId, java.io.File destFile) {
- if (fileId == null || destFile == null) {
- return;
- }
- try {
- Drive drive = buildDrive();
- Drive.Files.Get request = drive.files().get(fileId);
- File fileContent = request.execute();
- long size = fileContent.getSize();
- Drive.Files.Get downloadRequest = drive.files().get(fileId);
- MediaHttpDownloader downloader = downloadRequest.getMediaHttpDownloader();
- boolean isDirectDownload = false;
- // 文件小于20M时可以使用简单下载
- if (size < DIRECT_DOWNLOAD_MAX_SIZE) {
- isDirectDownload = true;
- }
- // 设置下载Range,非简单下载时必须设置该参数。
- downloader.setContentRange(0, size - 1);
- // 设置下载方式,默认使用非简单下载。当文件小于20M时可以使用简单下载,即设置为true。
- downloader.setDirectDownloadEnabled(isDirectDownload);
- // 设置进度回调通知
- downloadRequest.getMediaHttpDownloader().setProgressListener(new MediaHttpDownloaderProgressListener() {
- @Override
- public void progressChanged(MediaHttpDownloader downloader) throws IOException {
- //下载进度通知
- }
- });
- downloadRequest.executeContentAndDownloadTo(new FileOutputStream(destFile));
- } catch (Exception e) {
- Logger.e(TAG, "download file error:" + fileId + e.getMessage());
- if (destFile != null) {
- // 下载失败后,删除临时文件
- if (destFile.exists()) {
- boolean isDeleteSuccess = destFile.delete();
- if (!isDeleteSuccess) {
- Logger.e(TAG, "downLoadFile delete file fail");
- }
- }
- }
- }
- }
调用Files.list接口实现搜索文件:
- /**
- * 搜索文件
- * @param query 查询参数,详见Q查询语句
- * @param orderBy 排序字段
- * @param pageSize 分页大小
- * @param fields 设置请求返回时携带内容
- */
- private List<File> getFileList(String query, String orderBy, int pageSize, String fields){
- List<File> fileList = null;
- try{
- Drive drive = buildDrive();
- Drive.Files.List request = drive.files().list();
- String cursor = null;
- fileList = new ArrayList<>();
- do {
- FileList result = null;
- result = request.setQueryParam(query)
- .setOrderBy(orderBy)
- .setPageSize(pageSize)
- .setFields(fields)
- .execute();
- for (File file : result.getFiles()) {
- fileList.add(file);
- }
- cursor = result.getNextCursor();
- request.setCursor(cursor);
- }while(!StringUtils.isNullOrEmpty(cursor));
- }catch (Exception e) {
- Logger.e(TAG, "executeFilesList exception: " + e.toString());
- }
- return fileList;
- }
调用Files.subscribe接口注册指定文件变化通知channel,开启指定文件变化通知功能:
- /**
- * 注册指定文件变化通知channel,开启指定文件变化通知
- *
- * @param fileId 文件id
- */
- private void filesWatch(String fileId) {
- try {
- Drive drive = buildDrive();
- Channel content = new Channel();
- content.setType("web_hook");
- content.setUrl("https://xxxx.com"); //文件变化通知服务器地址,开发者需搭建该服务器
- Drive.Files.Subscribe request = drive.files().subscribe(fileId, content);
- Channel channel = request.execute();
- SharedPreferences prefs = context.getSharedPreferences("channel_config", Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = prefs.edit();
- editor.putString("id", channel.getId());
- editor.putString("resourceId", channel.getResourceId());
- editor.commit();
- } catch (Exception e) {
- Log.e(TAG, "Exception" + e.getCause());
- }
- }
华为云空间服务提供当文件发生变化时推送通知的能力,从而保持云端与本地文件同步。使用Changes功能需要第三方实现可实时接收变化的Server服务器,该Server可以接收变化并将变化信息实时推送给相应的客户端,客户端接收消息后可以及时刷新变化。
步骤1 第三方实现可以接收文件变化的Server服务器,需要将该Server的地址注册到Drive,Drive在发送变化消息时需要校验Server地址的有效性。
登录AppGallery Connect网站,将Server服务器域名注册到Drive方法如下图:

步骤2 开发者Server服务器需要能解析Drive发送的文件变化消息,Drive消息的消息头格式如下:
表1
参数 | 类型 | 可选 | 说明 |
X-HW-Channel-ID | varchar(255) | 必选 | 第三方开发者指定的,通过Changes.subscribe接口上报给Drive服务器的用户唯一标识。 |
X-HW-Channel-Token | varchar(255) | 可选 | 通过Changes.subscribe接口Drive服务器返回的Cursor,Server需要对Cursor进行校验。 |
X-HW-Channel-Expiration | varchar(255) | 可选 | Channel通知到期的日期和时间 格式例如:Tue,18 Jun 2019 14:21:46 GMT。 |
X-HW-Resource-ID | varchar(255) | 必选 | 资源ID,标识Channel正在监测的资源,当该资源变化时会推送通知。 |
X-HW-Resource-URI | varchar(255) | 必选 | 资源版本标识符。 |
X-HW-Resource-State | varchar(255) | 必选 | 资源状态,可选值: sync:订阅成功,Channel创建成功。 add:资源增加。 remove:资源被删除。 update:资源属性被更新。 recycle:资源移动到回收站。 unrecycle:资源从回收站移出。 change:资源变化。 |
X-HW-Message-Number | Int64 | 必选 | 消息号,后面的消息总是大于前面的,但是并不是连续的。Sync消息总是为1。 |
X-HW-Changed | varchar(255) | 可选 | Change的详细信息,state为update时有效,可选值。 content: 资源内容更新。 properties: 资源属性更新。 parents: 资源的父目录变化,暂时不涉及。 children: 资源的子文件变化。 |
步骤3 第三方Server服务器下发变化通知应用。
第三方Server服务器能够将Drive发送的变化消息下发通知到应用,让应用刷新变化内容;Drive不限制第三方Server下发变化通知的实现方式,但推荐开发者使用华为推送服务,华为推送服务已经实现了将服务器消息推送到指定应用的功能,使用华为推送服务需要对接HMS Core Push SDK,具体参考《消息推送服务》。若不使用华为推送服务,则不需要集成HMS Core Push SDK,但第三方Server需要自己实现消息推送的功能。
步骤4 获取StartCursor,通过subscribe注册推送通知功能。
应用调用Changes.getStartCursor接口,获取Changes.subscribe需要使用的cursor值,调用Changes.subscribe接口注册文件变化时的推送通知功能,该接口会返回注册成功后的Channel对象,开发者需要将Channel中的channelToken回传给第三方Server,用于后续Server接口消息的鉴权使用,同时开发者可以根据该Channel进行后续的刷新变化、停止推送通知等接口处理。
- /**
- * 注册文件变化通知
- * @param context 上下文环境
- * @param id UUID或其他字符串,唯一标识channel
- */
- private void watchChanges(Context context, String id) {
- try {
- Drive drive = buildDrive();
- StartCursor startCursor = drive.changes().getStartCursor().execute();
- String cursor = startCursor.getStartCursor();
- Channel content = new Channel();
- // id可以自定义,注意和Channels.stop接口保持一致
- content.setId(id);
- // 固定web_hook
- content.setType("web_hook");
- // 提供开发者用于接收变化的Server服务器地址
- content.setUrl("https://addr.xxx.com:8086/path/to/webhook");
- content.setExpirationTime(System.currentTimeMillis() + 300 * 1000L);
- Channel channel = drive.changes().subscribe(cursor, content).execute();
- // 需要将channelToken回传给三方Server服务器Url
- String channelToken = channel.getUserToken();
- SharedPreferences prefs = context.getSharedPreferences("channel_config", Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = prefs.edit();
- editor.putString("startPageVersion", cursor);
- editor.putString("resourceId", channel.getResourceId());
- editor.commit();
- } catch (Exception e) {
- Log.e(TAG, "watchChanges error: " + e.toString());
- }
- }
步骤5 获取用户文件变化。
应用收到第三方下发的通知后,调用Changes.list接口,获取用户文件变化,注意cursor入参为之前subscribe时传入的cursor。
- /**
- * 获取文件变化
- *
- * @param cursor 之前调用changes.subscribe传入的cursor
- */
- private List<Change> getChangesList(String cursor) {
- List<Change> changes = null;
- try {
- Drive drive = buildDrive();
- Drive.Changes.List listRequest = drive.changes().list(cursor);
- listRequest.setFields("*");
- ChangeList changeList = listRequest.execute();
- changes = changeList.getChanges();
- } catch (Exception e) {
- Log.e(TAG, "doChangesList error: " + e.toString());
- }
- return changes;
- }
华为云空间服务支持第三方应用关闭推送指定的Channel的变化通知,关闭后,该Channel不再收到文件变化通知。注意构造的Channel对象中的Id和resourceId与Changes中subscribe的Channel对象的Id和resourceId一致。
步骤1调用Drive.Builder.build接口构造Drive对象。
- private Drive buildDrive() {
- Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
- return service;
- }
步骤2获取之前注册推送通知时缓存的Id和resourceId,调用Channels.stop接口停止指定channel的文件变化通知。
- /**
- * 关闭指定的Channel
- * @param context 上下文环境
- * @param id UUID或其他字符串,唯一标识channel, 与subscribe接口的id保持一致
- */
- private void stopChannel(Context context, String id) {
- try {
- Drive drive = buildDrive();
- SharedPreferences preferences = context.getSharedPreferences("channel_config", Context.MODE_PRIVATE);
- String resourceId = preferences.getString("resourceId", "");
- Channel channel = new Channel();
- channel.setId(id);
- channel.setCategory("api#channel");
- channel.setResourceId(resourceId);
- Drive.Channels.Stop stopReq = drive.channels().stop(channel);
- stopReq.execute();
- } catch (Exception e) {
- Log.e(TAG, "stopChannels error: " + e.toString());
- }
- }
华为云空间服务支持用户对云端文件进行评论,并对评论进行查看、更新和删除操作。
步骤1调用Drive.Builder.build接口构造Drive对象。
- private Drive buildDrive() {
- Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
- return service;
- }
步骤2调用Comments
调用Comments.Create接口创建文件评论:
- /**
- * 创建文件评论
- *
- * @param fileId 文件id
- */
- private Comment createComments(String fileId) {
- Comment comment = null;
- Drive drive = buildDrive();
- try {
- Comment content = new Comment();
- content.setDescription("interface test");
- content.setCreatedTime(new DateTime(System.currentTimeMillis()));
- comment = drive.comments().create(fileId, content).setFields("*").execute();
- } catch (Exception ex) {
- Log.e(TAG, "createComments error: " + ex.toString());
- }
- return comment;
- }
调用Comments.List接口获取文件评论列表:
- /**
- * 获取文件评论列表
- *
- * @param fileId 文件id
- */
- private List<Comment> listComments(String fileId) {
- Drive drive = buildDrive();
- ArrayList<Comment> commentArrayList = new ArrayList<>();
- String nextCursor = null;
- try {
- Drive.Comments.List request = drive.comments().list(fileId);
- do {
- if (nextCursor != null) {
- request.setCursor(nextCursor);
- }
- CommentList commentList = request.setPageSize(100).setFields("*").execute();
- ArrayList<Comment> comments = (ArrayList<Comment>) commentList.getComments();
- if (comments == null) {
- break;
- }
- commentArrayList.addAll(comments);
- nextCursor = commentList.getNextCursor();
- } while (!StringUtils.isNullOrEmpty(nextCursor));
- } catch (IOException e) {
- Logger.e(TAG, "comments list error: " + e.toString());
- }
- return commentArrayList;
- }
调用Comments.Get接口获取文件评论详情:
- /**
- * 获取文件评论详情
- *
- * @param fileId 文件id
- * @param commentId 评论id
- */
- private Comment getComments(String fileId, String commentId) {
- Comment comment = null;
- Drive drive = buildDrive();
- try {
- comment = drive.comments().get(fileId, commentId).setFields("*").execute();
- Log.d(TAG, "comment: " + comment.getDescription());
- } catch (Exception ex) {
- Log.e(TAG, "getComments error: " + ex.toString());
- }
- return comment;
- }
调用Comments.Update接口更新文件评论:
- /**
- * 更新文件评论
- *
- * @param fileId 文件id
- * @param commentId 评论id
- */
- private void updateComments(String fileId, String commentId) {
- Drive drive = buildDrive();
- try {
- Comment content = new Comment();
- content.setDescription("update interface test");
- drive.comments().update(fileId, commentId, content).execute();
- } catch (Exception ex) {
- Log.e(TAG, "updateComments error: " + ex.toString());
- }
- }
调用Comments.Delete接口删除文件评论:
- /**
- * 删除文件评论
- *
- * @param fileId 文件id
- * @param commentId 评论id
- */
- private void deleteComments(String fileId, String commentId) {
- Drive drive = buildDrive();
- try {
- drive.comments().delete(fileId, commentId).execute();
- } catch (Exception ex) {
- Log.e(TAG, "deleteComments error: " + ex.toString());
- }
- }
华为云空间服务支持用户对云端文件的评论进行行回复,并对回复进行查看、更新和删除操作。
步骤1调用Drive.Builder.build接口构造Drive对象。
- private Drive buildDrive() {
- Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
- return service;
- }
步骤2调用Replies接口能力
调用Replies.Create接口创建评论回复:
- /**
- * 创建文件评论回复
- *
- * @param fileId 文件id
- * @param commentId 文件评论id
- */
- private Reply createReplies(String fileId, String commentId) {
- Reply replyResponse = null;
- Drive drive = buildDrive();
- try {
- Reply reply = new Reply();
- reply.setDescription("interface test reply");
- reply.setOperate("resolve");
- replyResponse = drive.replies().create(fileId, commentId, reply).setFields("*").execute();
- } catch (Exception ex) {
- Log.e(TAG, "createReplies error: " + ex.toString());
- }
- return replyResponse;
- }
调用Replies.List接口获取评论回复列表:
- /**
- * 获取评论回复列表
- *
- * @param fileId 文件id
- * @param commentId 评论id
- */
- private List<Reply> listReplies(String fileId, String commentId) {
- Drive drive = buildDrive();
- List<Reply> replyResponse = new ArrayList<>();
- String nextCursor = null;
- try {
- Drive.Replies.List listReq = drive.replies().list(fileId, commentId);
- do {
- if (nextCursor != null) {
- listReq.setCursor(nextCursor);
- }
- ReplyList replyList = listReq.setFields("*").execute();
- List<Reply> replies = replyList.getReplies();
- if (replies == null) {
- break;
- }
- replyResponse.addAll(replies);
- nextCursor = replyList.getNextCursor();
- } while (StringUtils.isNullOrEmpty(nextCursor));
- } catch (Exception ex) {
- Log.e(TAG, "listReplies error: " + ex.toString());
- }
- return replyResponse;
- }
调用Replies.Get接口获取评论回复详情:
- /**
- * 获取评论回复详情
- *
- * @param fileId 文件id
- * @param commentId 评论id
- * @param replyId 回复id
- */
- private Reply getReplies(String fileId, String commentId, String replyId) {
- Reply reply = null;
- Drive drive = buildDrive();
- try {
- reply = drive.replies().get(fileId, commentId, replyId).setFields("*").execute();
- } catch (Exception ex) {
- Log.e(TAG, "getReplies error: " + ex.toString());
- }
- return reply;
- }
调用Replies.Update接口更新评论回复:
- /**
- * 更新评论回复
- *
- * @param fileId 文件id
- * @param commenId 评论id
- * @param replyId 回复id
- */
- private void updateReplies(String fileId, String commentId, String replyId) {
- Drive drive = buildDrive();
- try {
- Reply reply = new Reply();
- reply.setDescription("interface test reply");
- reply.setOperate("reopen");
- drive.replies().update(fileId, commentId, replyId, reply).execute();
- } catch (Exception ex) {
- Log.e(TAG, "updateReplies error: " + ex.toString());
- }
- }
调用Replies.Delete接口删除评论回复:
- /**
- * 删除评论回复
- *
- * @param fileId 文件id
- * @param commenId 评论id
- * @param replyId 回复id
- */
- private void deleteReplies(String fileId, String commentId, String replyId) {
- Drive drive = buildDrive();
- try {
- drive.replies().delete(fileId, commentId, replyId).execute();
- } catch (Exception ex) {
- Log.e(TAG, "deleteReplies error: " + ex.toString());
- }
- }
华为云空间服务支持第三方应用对某些接口进行批量操作,具体接口如下:文件(夹)的批量操作,如创建文件夹、创建文件元数据、复制、更新、删除、订阅等,评论及回复的批量操作,如评论及回复的新增、更新、删除等。
以批量创建文件夹为例来说明具体开发步骤:
步骤1 调用Drive.Builder.build接口构造Drive对象。
- private Drive buildDrive() {
- Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
- return service;
- }
步骤2 创建JsonBatchCallback回调对象,调用Drive的batch函数获取BatchRequest对象,再调用Files.Create的queue函数将操作添加到队列中,再执行BatchRequest.execute即可完成批量操作。
- /**
- * 批量创建回调
- */
- JsonBatchCallback<File> callback = new JsonBatchCallback<File>() {
- @Override
- public void onFailure(JsonError e, HttpHeaders responseHeaders) throws IOException {
- Logger.i(TAG, "callback error: " + e.toString());
- }
- @Override
- public void onSuccess(File file, HttpHeaders responseHeaders) throws IOException {
- Logger.i(TAG, "callback sucessful: " + file.toString());
- }
- };
- /**
- * 批量创建目录
- */
- private void batchCreateDirectory() {
- Drive drive = buildDrive();
- BatchRequest batch = drive.batch();
- try {
- for (int i = 0; i < 2; i++) {
- Map<String, String> appProperties = new HashMap<>();
- appProperties.put("appProperties", "property");
- SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
- String dirName = formatter.format(new Date()) + "_" + i;
- Logger.i(TAG, "executeFilesCreate: " + dirName);
- File file = new File();
- file.setFileName(dirName)
- .setAppSettings(appProperties)
- .setMimeType("application/vnd.huawei-apps.folder");
- Drive.Files.Create create = drive.files().create(file);
- create.queue(batch, callback);
- }
- batch.execute();
- } catch (Exception e) {
- Logger.e(TAG, "batchCreateDirectory error: " + e.toString());
- }
- }