目录

This section describes the procedures for integrating HUAWEI Drive Kit into your app and provides relevant guidance to help you quickly learn the client APIs provided by HUAWEI Drive Kit and the methods of calling these APIs. You may choose to read any applicable subsections below based on your specific use cases.

1 Functions

Major capabilities provided by the Drive SDK and the corresponding call methods include:

  1. Obtaining authentication information.

  2. Obtaining user information and the authorization page using the About.get() API.

  3. Implementing file management and search functions using the Files APIs. 

  4. Registering channels for tracking file changes and enabling the file change notification function using the Changes APIs.

  5. Commenting on files using the Comments API.

  6. Replying to comments using the Replies API.

2 Obtaining Authentication Information

2.1 Use Case

HUAWEI ID is required for a user uses to access and manage their files in Drive. Before your app can use the Drive SDK, it needs to prompt the user to sign in with their HUAWEI ID. After the user signs in, your app saves relevant user information for calling Drive SDK APIs later.

2.2 Service Process

The figure below shows the basic service process.

2.3 Development Procedure

Step 1 Integrate the HMS SDK.

To use the Drive SDK, your app needs to obtain user information through the HMS SDK first. For details, please refer to Integrating the Drive SDK and HMS SDK.

Step 2 Set the HMS scope.

Set the Drive scope by calling the HuaweiIdAuthParamsHelper.setScopeList API provided by the HMS SDK to obtain the permission to access Drive APIs.

  1. List<Scope> scopeList = new LinkedList<>();
  2. scopeList.add(HuaweiIdAuthAPIManager.HUAWEIID_BASE_SCOPE);// Basic account permissions
  3. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE));// All permissions, except permissions for the app folder.
  4. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_FILE));// Permissions to view and manage files.
  5. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_METADATA));// Permissions to view and manage file metadata, excluding file content.
  6. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_METADATA_READONLY));// Permissions only for viewing file metadata, excluding file entities.
  7. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_READONLY));// Permissions to view file metadata and content.
  8. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_APPDATA));// Permissions to view and manage app files.
  9. HuaweiIdAuthParams params = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
  10.         .setAccessToken()
  11.         .setIdToken()
  12.         .setScopeList(scopeList)
  13.         .createParams();

The access permissions vary according to the Drive scope. You may apply for the permissions as needed. For details, please refer to Signing In with HUAWEI ID.

Step 3 Store authentication information.

After obtaining the user information, save the unionId and AccessToken  of the user for calling the Drive SDK whenever needed. The following provides an example implementation method. You may use another implementation method if necessary.

Sample code:

Creates the CredentialManager class.

  1. /**
  2. * Credential management class
  3. * <p>
  4. * since 1.0
  5. */
  6. public class CredentialManager {
  7.     /**
  8.     * Drive authentication information.
  9.     */
  10.     private DriveCredential mCredential;
  11.     private CredentialManager() {
  12.     }
  13.     private static class InnerHolder {
  14.         private static CredentialManager sInstance = new CredentialManager();
  15.     }
  16.    /**
  17.     * Singleton CredentialManager instance.
  18.     *
  19.     * @return CredentialManager
  20.     */
  21.    public static CredentialManager getInstance() {
  22.         return InnerHolder.sInstance;
  23.     }
  24.    /**
  25.     * Initialize Drive based on the context and HUAWEI ID information including unionId, countrycode, and accessToken.
  26.     * When the current accessToken expires, register an AccessMethod and obtain a new accessToken. The value of refreshAT cannot be null.
  27.     *
  28.     * @param unionID   unionID in HwID
  29.     * @param at        access token
  30.     * @param refreshAT Update the accessToken callback function, without carrying null values.
  31.     */
  32.    public int init(String unionID, String at, DriveCredential.AccessMethod refreshAT) {
  33.         if (StringUtils.isNullOrEmpty(unionID) || StringUtils.isNullOrEmpty(at)) {
  34.             return DriveCode.ERROR;
  35.         }
  36.         DriveCredential.Builder builder = new DriveCredential.Builder(unionID, refreshAT);
  37.         mCredential = builder.build().setAccessToken(at);
  38.         return DriveCode.SUCCESS;
  39.     }
  40.    /**
  41.     * Obtain DriveCredential.
  42.     *
  43.     * @return DriveCredential
  44.     */
  45.    public DriveCredential getCredential() {
  46.         return mCredential;
  47.     }
  48.     /**
  49.     * Exit Drive and clear all cache information generated during use.
  50.     */
  51.     public void exit(Context context) {
  52.         // Clear cache files.
  53.         deleteFile(context.getCacheDir());
  54.         deleteFile(context.getFilesDir());
  55.     }
  56.    /**
  57.     * Delete cache files.
  58.     *
  59.     * @param file Designated cache file
  60.     */
  61.     private static void deleteFile(java.io.File file) {
  62.         if (null == file || !file.exists()) {
  63.             return;
  64.         }
  65.         if (file.isDirectory()) {
  66.             java.io.File[] files = file.listFiles();
  67.             if (files != null) {
  68.                 for (java.io.File f : files) {
  69.                     deleteFile(f);
  70.                 }
  71.             }
  72.         }
  73.     }
  74. }

Call initDrive in the onActivityResult callback after the user signs in.

  1. private static DriveCredential.AccessMethod refreshAT = new DriveCredential.AccessMethod() {
  2.    @Override
  3.    public String refreshToken() {
  4.        // Obtain a new access token through the HMS SDK.
  5.        return refreshAccessToken();
  6.    }
  7. };
  8. private void initDrive() {
  9.    // signInHuaweiId is the HUAWEI ID that the user used to sign in. Based on signInHuaweiId, obtain unionId and AccessToken.
  10.    final String unionID = signInHuaweiId.getUnionId();
  11.    final String accessToken = signInHuaweiId.getAccessToken();


  12.    int returnCode = CredentialManager.getInstance().init(unionID, accessToken, refreshAT);
  13.    if (DriveCode.SUCCESS == returnCode) {
  14.        //Jump to the app home page after successful initialization.
  15.        jumpToMainActivity();
  16.    }
  17. }
NOTICE:
After obtaining the authentication information, your app must check whether the user's security policy needs to be updated. For details, please refer to Obtaining User Information.

3 Obtaining User Information

3.1 Use Case

By calling the About.get API, your app can obtain a user's Drive information, such as its storage quota limit and maximum size of a file that can be uploaded by the user.

3.2 Development Procedure

Step 1 Call the Drive.Builder.build API to create the Drive object.

  1. private Drive buildDrive() {  
  2.    Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();  
  3.    return service;  
  4. }

Step 2 Call the About.get API to obtain user information. setFields("*") indicates that all fields need to be returned.

  1. private About getAbout() {
  2.    About response = null;
  3.    try {
  4.        Drive drive = buildDrive();
  5.        Drive.About about = drive.about();
  6.        response = about.get().setFields("*").execute();
  7.        String res = response.toString();
  8.    } catch (Exception e) {
  9.        Log.e(TAG, "getInfo error: " + e.toString());
  10.    }
  11.    return response;
  12. }
CAUTION:
Call the About.get in the subthread. The process of obtaining user information takes a while and requires an internet connection

Step 3 Check the value of needUpdate in the response returned by the About.get API. If it is true, the user's security policy needs to be updated. In this case, your app jumps to the authorization page based on the returned address and continues to provide services after obtaining authorization from the user.

  1. /**
  2. *  Check whether the user needs to be prompted to update the protocol.
  3. *
  4. * @param about About response that is returned.
  5. */
  6. private void checkUpdateProtocol(About about) {
  7.    if (about == null) {
  8.        return;
  9.    }
  10.    Log.d(TAG, "checkUpdate: " + about.toString());
  11.    Object updateValue = about.get("needUpdate");
  12.    boolean isNeedUpdate = false;
  13.    if (updateValue instanceof Boolean) {
  14.        isNeedUpdate = (Boolean) updateValue;
  15.    }
  16.    if (!isNeedUpdate) {
  17.        return;
  18.    }
  19.    Object urlValue = about.get("updateUrl");
  20.    String url = "";
  21.    if (urlValue instanceof String) {
  22.        url = (String) urlValue;
  23.    }
  24.    if (TextUtils.isEmpty(url)) {
  25.        return;
  26.    }
  27.    Uri uri = Uri.parse(url);
  28.    if (!"https".equals(uri.getScheme())) {
  29.        return;
  30.    }
  31.    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
  32.    try {
  33.        startActivity(intent);
  34.    } catch (ActivityNotFoundException e) {
  35.        Logger.e(TAG, "Activity Not found");
  36.    }
  37. }

Notice:
The needUpdate field is optional, and the About.get API may not return this field.

4 Managing and Searching for Files

4.1 Use Case

File management is a core capability of HUAWEI Drive Kit. It enables users to conveniently manage and edit files in Drive, including creating, listing, copying, modifying, deleting, recycling, and searching for files.

4.2 Development Procedure

Step 1 Call the Drive.Builder.build API to create the Drive object.  

  1. private Drive buildDrive() {  
  2.    Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();  
  3.    return service;  
  4. }

Step 2 Call the Files APIs.

NOTE:

Constants used in the sample code:

private static final int DIRECT_UPLOAD_MAX_SIZE = 20 * 1024 * 1024;

private static final int DIRECT_DOWNLOAD_MAX_SIZE = 20 * 1024 * 1024;

Call the Files.create API to create a folder.

  1. /**
  2. * Create a folder.
  3. */
  4. private File createDirectory() {
  5.    File directory = null;
  6.    try {
  7.        Drive drive = buildDrive();
  8.        Map<String, String> appProperties = new HashMap<>();
  9.        appProperties.put("appProperties", "property");
  10.        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
  11.        String dirName = formatter.format(new Date());
  12.        File file = new File();
  13.        file.setFileName(dirName)
  14.                .setAppSettings(appProperties)
  15.                .setMimeType("application/vnd.huawei-apps.folder");
  16.        directory = drive.files().create(file).execute();
  17.    } catch (Exception e) {
  18.        Logger.e(TAG, "createDirectory error: " + e.toString());
  19.    }
  20.    return directory;
  21. }

Call the Files.create API to create a file. The are two methods for uploading a file: direct upload and resumable upload. The direct upload method allows a file of up to 20 MB to be uploaded while the resumable upload method does not have such a limit. The direct upload method is recommended for files smaller than 5 MB and the resumable upload method for files larger than 5 MB. 

Method 1: Directly upload the file.

  1. /**    
  2. * Upload a file. This method supports resumable upload.  
  3. * (The upload operation resumes after it is interrupted by a communication failure, for example, network interruption.)
  4. *    
  5. * @param filePath  File path.
  6. * @param parentId  ID of the folder to which the file is to be uploaded.
  7. * @param thumbnailImageBuffer Thumbnail data.
  8. * @param thumbnailMimeType MIME type of the thumbnail.
  9. */  
  10. private void createFile(String filePath, String parentId, byte[] thumbnailImageBuffer, String thumbnailMimeType) {
  11.    try {
  12.        if (filePath == null) {
  13.            Logger.e(TAG, "createFile error, filePath is null.");
  14.            return;
  15.        }
  16.        java.io.File file = new java.io.File(filePath);
  17.        FileContent fileContent = new FileContent(null, file);
  18.        // Set thumbnail data.
  19.        File.ContentExtras contentExtras = new File.ContentExtras();
  20.        File.ContentExtras.Thumbnail thumbnail = new File.ContentExtras.Thumbnail();
  21.        thumbnail.setContent(Base64.encodeBase64String(thumbnailImageBuffer));
  22.        thumbnail.setMimeType(thumbnailMimeType);
  23.        contentExtras.setThumbnail(thumbnail);
  24.        File content = new File()
  25.                .setFileName(file.getName())
  26.                .setParentFolder(Collections.singletonList(parentId))
  27.                .setContentExtras(contentExtras);
  28.        Drive drive = buildDrive();
  29.        Drive.Files.Create request = drive.files().create(content, fileContent);
  30.        boolean isDirectUpload = false;
  31.        // Directly upload the file if it is smaller than 20 MB.  
  32.        if (file.length() < DIRECT_UPLOAD_MAX_SIZE) {
  33.            isDirectUpload = true;
  34.        }
  35.        // Set the upload mode. By default, resumable upload is used. If the file is smaller than 20 MB, set this parameter to true.
  36.        request.getMediaHttpUploader().setDirectUploadEnabled(isDirectUpload);
  37.        request.execute();
  38.    } catch (Exception e) {
  39.        Logger.e(TAG, "createFile exception: " + filePath + e.toString());
  40.    }
  41. }

Method 2: Upload the file using InputStream.

  1. /**
  2. * Upload the file using InputStream.
  3. *
  4. * @param inputStream Input stream, from which file data is read.
  5. * @param parentId  ID of the folder to which the file is to be uploaded.
  6. * @param mimeType MIME type, for example, image (jpeg) and video (mp4).
  7. * @param inputStreamLength Stream length.
  8. */
  9. private void createFile(InputStream inputStream, String parentId, String mimeType, int inputStreamLength) {
  10.    try {
  11.        InputStreamContent streamContent = new InputStreamContent(mimeType, inputStream);
  12.        streamContent.setLength(inputStreamLength);
  13.        File content = new File()
  14.                .setFileName("video.mp4")
  15.                .setParentFolder(Collections.singletonList(parentId));
  16.        Drive drive = buildDrive();
  17.        drive.files().create(content, streamContent).execute();
  18.    } catch (Exception e) {
  19.        Logger.e(TAG, "createFile exception: " + e.toString());
  20.    }
  21. }

Call the Files.copy API to copy the file.

  1. /**  
  2. * Copy the file to the designated folder.
  3. *      
  4. * @param file File to be copied.
  5. * @param dstDir Designated folder.
  6. */  
  7. private void copyFile(File file, ArrayList<String> dstDir) {  
  8.    try {  
  9.        File copyFile = new File();
  10.            if (file == null || file.getFileName() == null ||dstDir == null) {
  11.                Log.e(TAG, "copyFile arguments error");
  12.                return;
  13.            }
  14.            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
  15.            String suffix = formatter.format(new Date());
  16.            copyFile.setFileName(file.getFileName() + "_copy" +  "_" + suffix);
  17.            copyFile.setDescription("copyFile");
  18.            copyFile.setParentFolder(dstDir);
  19.            copyFile.setFavorite(true);
  20.            copyFile.setEditedTime(new DateTime(System.currentTimeMillis()));
  21.            Drive drive = buildDrive();
  22.            Drive.Files.Copy copyFileReq = drive.files().copy(file.getId(), copyFile);
  23.            copyFileReq.setFields("*");
  24.            File result = copyFileReq.execute();  
  25.    } catch (IOException ex) {  
  26.        Log.e(TAG, "copyFile error: " + ex.toString());  
  27.    }  
  28. }

Call the Files.update API to modify the metadata of the file or folder.

  1. /**  
  2. * Modify the file or folder. The value of MIMEType indicates whether it is a file or a folder.  
  3. *  
  4. * @param file  File or folder to be modified.  
  5. */  
  6. private void updateFile(File file) {  
  7.    try {  
  8.        if (file == null) {  
  9.            Logger.e(TAG, "updateFile error, need to create file.");  
  10.            return;  
  11.        }  
  12.        Drive drive = buildDrive();  
  13.        File updateFile = new File();  
  14.        updateFile.setFileName(file.getFileName() +"_update")  
  15.                .setMimeType("application/vnd.huawei-apps.folder")  
  16.                .setDescription("update folder")  
  17.                .setFavorite(true);  
  18.        drive.files().update(file.getId(), updateFile).execute();  
  19.    } catch (Exception e) {  
  20.        Logger.e(TAG, "updateFile error: " + e.toString());  
  21.    }  
  22. }

Call the Files.update API to modify the metadata or content of the file.

  1. /**    
  2. * Modify the file.
  3. *    
  4. * @param oldFile File to be modified.
  5. * @param newFilePath Path storing the modified file.
  6. */  
  7. private void updateFile(File oldFile, String newFilePath) {  
  8.     try {  
  9.         if (oldFile == null || TextUtils.isEmpty(newFilePath)) {  
  10.             Logger.e(TAG, "updateFile error, need to create file.");  
  11.             return;  
  12.         }  
  13.         java.io.File sourceFile = new java.io.File(newFilePath);  
  14.         FileContent fileContent = new FileContent(null, sourceFile);  
  15.         File updateFile = new File();  
  16.         updateFile.setFileName(oldFile.getFileName() + "_update")  
  17.                 .setDescription("update folder")  
  18.                 .setFavorite(true);  
  19.         Drive drive = buildDrive();  
  20.         Drive.Files.Update update = drive.files().update(oldFile.getId(), updateFile, fileContent);  
  21.         boolean isDirectUpload = false;  
  22.         // Directly upload the file if it is smaller than 20 MB.  
  23.         if (sourceFile.length() < DIRECT_UPLOAD_MAX_SIZE) {  
  24.             isDirectUpload = true;  
  25.         }  
  26.         // Set the upload mode. By default, resumable upload is used. If the file is smaller than 20 MB, set this parameter to true.
  27.         update.getMediaHttpUploader().setDirectUploadEnabled(isDirectUpload);  
  28.         update.execute();  
  29.     } catch (Exception e) {  
  30.         Logger.e(TAG, "updateFile error: " + e.toString());  
  31.     }  
  32. }

Call the Files.delete API to permanently delete a file or folder.

  1. /**  
  2. * Permanently delete a file or folder.
  3. *  
  4. * @param file  File or folder to be deleted.
  5. */  
  6. private void deleteFile(File file) {  
  7.    try {  
  8.        Drive drive = buildDrive();  
  9.        Drive.Files.Delete deleteFile = drive.files().delete(file.getId());  
  10.        deleteFile.execute();  
  11.    } catch (IOException ex) {  
  12.        Log.e(TAG, "deleteFile error: " + ex.toString());  
  13.    }  
  14. }

Call the Files.get API to obtain the file metadata.

  1. /**
  2. * Obtain the file metadata.
  3. *
  4. * @param fileId File ID.
  5. */
  6. private File getFileMetadata(String fileId) {
  7.    File file = null;
  8.    try {
  9.        Drive drive = buildDrive();
  10.        Drive.Files.Get request = drive.files().get(fileId);
  11.        request.setFields("*");
  12.        file = request.execute();
  13.    } catch (Exception e) {
  14.        Logger.e(TAG, "get metadata error: " + e.toString());
  15.    }
  16.    return file;
  17. }

Call the Files.get API to download the file metadata and content. A file of any size can be downloaded. To download a file smaller than 20 MB, set directDownloadEnabled to true. Then, simply download the file through a network request. 

  1. /**  
  2. * Download the file metadata and content.
  3. *  
  4. * @param fileId  File ID.
  5. * @param destFile Target file.
  6. */
  7. private void downLoadFile(String fileId, java.io.File destFile) {
  8.    if (fileId == null || destFile == null) {
  9.        return;
  10.    }
  11.    try {
  12.        Drive drive = buildDrive();
  13.        Drive.Files.Get request = drive.files().get(fileId);
  14.        File fileContent = request.execute();
  15.        long size = fileContent.getSize();
  16.        Drive.Files.Get downloadRequest = drive.files().get(fileId);
  17.        MediaHttpDownloader downloader = downloadRequest.getMediaHttpDownloader();
  18.        boolean isDirectDownload = false;
  19.        // Download the file using the simple download method if it is smaller than 20 MB.  
  20.        if (size < DIRECT_DOWNLOAD_MAX_SIZE) {
  21.            isDirectDownload = true;
  22.        }
  23.        // Set the range. This parameter is mandatory when the simple download method is not uesd.  
  24.        downloader.setContentRange(0, size - 1);
  25.        // Set the download method. By default, a download method rather than simple download is used. If the file is smaller than 20 MB, set this parameter to true.
  26.        downloader.setDirectDownloadEnabled(isDirectDownload);
  27.        // Set the progress callback listener.
  28.        downloadRequest.getMediaHttpDownloader().setProgressListener(new MediaHttpDownloaderProgressListener() {
  29.            @Override
  30.            public void progressChanged(MediaHttpDownloader downloader) throws IOException {
  31.                // Download progress notification.
  32.            }
  33.        });
  34.        downloadRequest.executeContentAndDownloadTo(new FileOutputStream(destFile));
  35.    } catch (Exception e) {
  36.        Logger.e(TAG, "download file error:" + fileId + e.getMessage());
  37.        if (destFile != null) {
  38.            // If the download fails, delete the temporary file.
  39.            if (destFile.exists()) {
  40.                boolean isDeleteSuccess = destFile.delete();
  41.                if (!isDeleteSuccess) {
  42.                    Logger.e(TAG, "downLoadFile delete file fail");
  43.                }
  44.            }
  45.        }
  46.    }
  47. }

Call the Files.list API to search for files.

  1. /**
  2. * Search for files.
  1. * @param query Query parameter. For details, please refer to Q statements.
  2. * @param orderBy Sorting field.
  3. * @param pageSize Maximum number of files to return per page.
  4. * @param fields Fields to be contained in the response.
  5. */
  6. private List<File> getFileList(String query, String orderBy, int pageSize, String fields){
  7.    List<File> fileList = null;
  8.    try{
  9.         Drive drive = buildDrive();
  10.         Drive.Files.List request = drive.files().list();
  11.         String cursor = null;
  12.         fileList = new ArrayList<>();
  13.         do {
  14.             FileList result = null;
  15.             result = request.setQueryParam(query)
  16.                 .setOrderBy(orderBy)
  17.                 .setPageSize(pageSize)
  18.                 .setFields(fields)
  19.                 .execute();
  20.            for (File file : result.getFiles()) {
  21.                fileList.add(file);
  22.            }
  23.            cursor = result.getNextCursor();
  24.            request.setCursor(cursor);
  25.        }while(!StringUtils.isNullOrEmpty(cursor));
  26.    }catch (Exception e) {
  27.            Logger.e(TAG, "executeFilesList exception: " + e.toString());
  28.     }
  29.     return fileList;
  30. }

Call the Files.subscribe API to register the channel for tracking changes made to the designated file and enable change notification for the file.

  1. /**    
  2. * register to the channel for tracking changes made to the designated file and enable change notification for the file.
  3. *    
  4. * @param fileId File ID    
  5. */  
  6. private void filesWatch(String fileId) {
  7.    try {
  8.        Drive drive = buildDrive();
  9.        Channel content = new Channel();
  10.        content.setType("web_hook");
  11.        content.setUrl("https://xxxx.com"); // Address of the server to which file changes will be sent. You need to build the server.  
  12.        Drive.Files.Subscribe request = drive.files().subscribe(fileId, content);
  13.        Channel channel = request.execute();
  14.        SharedPreferences prefs = context.getSharedPreferences("channel_config", Context.MODE_PRIVATE);
  15.        SharedPreferences.Editor editor = prefs.edit();
  16.        editor.putString("id", channel.getId());
  17.        editor.putString("resourceId", channel.getResourceId());
  18.        editor.commit();
  19.    } catch (Exception e) {
  20.        Log.e(TAG, "Exception" + e.getCause());
  21.    }
  22. }
CAUTION:
Call the Files APIs in the subthread. File management takes a while and requires an Internet connetion.

5 Enabling File Change Notification

5.1 Use Case

HUAWEI Drive Kit enables your app to send file change notifications to users so that they can synchronize files in the cloud and those stored locally in time. To use the Changes API, you need a server that can receive changes and push them to your app in real time. After receiving the changes, the app updates local files at the request of the user.

5.2 Development Procedure

Step 1 Register your server URL with Drive.

Drive will check the validity of the server URL before sending a file change notification.

Sign in to AppGallery Connect and register your server domain name with Drive, as shown in the figure below.

Step 2 Configure the server to parse the file change notification sent by Drive.

The header of the notification is in the following format:

Table 2-1

Parameter

Type

Mandatory/Optional

Description

X-HW-Channel-ID

varchar(255)

Mandatory

Unique user ID that you defined, which is sent to the Drive server through the Changes.subscribe API.

X-HW-Channel-Token

varchar(255)

Optional

User token that you defined, which is contained in the request for calling the Changes.subscribe API and will be verified by your server.

X-HW-Channel-Expiration

varchar(255)

Optional

Date and time when the notification channel expires.

Format: Tue, 18 Jun 2019 14:21:46 GMT.

X-HW-Resource-ID

varchar(255)

Mandatory

Resource ID, which identifies the resource being tracked on this channel. When the resource changes, a notification will be sent.

X-HW-Resource-URI

varchar(255)

Mandatory

Version-specific identifier for the resource.

X-HW-Resource-State

varchar(255)

Mandatory

Resource state. Values:

sync: The subscription is successful and the channel is created successfully.

add: The resource is added.

remove: The resource has been deleted.

update: Resource properties have been updated.

recycle: The resource has been moved to recycle bin.

unrecycle: The resource has been restored from the recycle bin.

change: The resource has been changed.

X-HW-Message-Number

Int64

Mandatory

Message number. A later message number is always greater than an earlier one, but the numbers may not be consecutive. The number of a sync message is always 1.

X-HW-Changed

varchar(255)

Optional

File change details. This parameter is   valid only when the value of State is update.

content: Resource content has been updated.

properties: Resource properties have been updated.

parents: The parent folder of the resource has been changed. Currently this value is not used.

children: Sub-files of the resource have been changed.

Step 3 Configure the server to send the change notification to the app.

Configure your server to send the change notification to your app if files in the cloud have been updated. Drive does not limit how your server delivers the change notification. However, we recommend that you use the HUAWEI Push service, which enables your server to deliver notifications to designated apps. 

To use the HUAWEI Push service, you will need to integrate the HMS Core Push SDK ("Push SDK") into your app. For details, please refer to HUAWEI Push Service Introduction. If you do not use the HUAWEI Push service, ensure that your server implements the push function.

Step 4 Configure your server to obtain startCursor and subscribe to the file change notification function through the Changes.subscribe API.

Configure your app to call the Changes.getStartCursor API to obtain the cursor value required by the Changes.subscribe API and then calls the Changes.subscribe API to subscribe to the file change notification function. The Changes.subscribe API will return the subscribed channel object and you app needs to pass the channelToken in the channel object to your server, for authenticating subsequent messages returned. In addition, you can also configure your app to perform desired operations such as updating changes and stopping file change notification based on the Channel object.

  1. /**  
  2. * Subscribe to file change notification.
  3. * @param context Context
  4. * @param id UUID or similar unique string that identifies this channel
  5. */  
  6. private void watchChanges(Context context, String id) {  
  7.    try {  
  8.        Drive drive = buildDrive();  
  9.        StartCursor startCursor = drive.changes().getStartCursor().execute();  
  10.        String cursor = startCursor.getStartCursor();  
  11.        Channel content = new Channel();  
  12.        // id can be customized but must be consistent with the one used in the Channels.stop API.
  13.        content.setId(id);  
  14.        // Fixed value: web_hook
  15.        content.setType("web_hook");  
  16.        // Server URL for receiving changes
  17.        content.setUrl("https://addr.xxx.com:8086/path/to/webhook");  
  18.        content.setExpirationTime(System.currentTimeMillis() + 300 * 1000L);  
  19.        Channel channel = drive.changes().subscribe(cursor, content).execute();  
  20.        // Return the channelToken to the server URL.
  21.        String channelToken = channel.getUserToken();
  22.        SharedPreferences prefs =  
  23.        context.getSharedPreferences("channel_config", Context.MODE_PRIVATE);  
  24.        SharedPreferences.Editor editor = prefs.edit();  
  25.        editor.putString("startPageVersion", cursor);  
  26.        editor.putString("resourceId", channel.getResourceId());  
  27.        editor.commit();  
  28.    } catch (Exception e) {  
  29.        Log.e(TAG, "watchChanges error: " + e.toString());  
  30.    }  
  31. }
CAUTION:
Call the Changes.getStartCursor API and  Changes.subscribe API in the subthread. The related operation process takes a while and requires an Internet connection.

Step 5 Configure your app to retrieve file changes.

After receiving the notification, the app calls the Changes.list API to retrieve user file changes. Note that the input parameter cursor is the one that the Changes.getStartCursor API passed to the Changes.subscribe API.

  1. /**
  2. * Retrieve file changes.
  3. *
  4. * @param cursor  Cursor passed to the Changes.subscribe API.
  5. */
  6. private List<Change> getChangesList(String cursor) {
  7.    List<Change> changes = null;
  8.    try {
  9.        Drive drive = buildDrive();
  10.        Drive.Changes.List listRequest = drive.changes().list(cursor);
  11.        listRequest.setFields("*");
  12.        ChangeList changeList = listRequest.execute();
  13.        changes = changeList.getChanges();
  14.    } catch (Exception e) {
  15.        Log.e(TAG, "doChangesList error: " + e.toString());
  16.    }
  17.    return changes;
  18. }
CAUTION:
Call the Changes.list API in the subthread. File Change retrieval takes a while and requires an Internet connection.

6 Stopping File Change Notification

6.1 Use Case

HUAWEI Drive Kit allows your app to disable sending file change notifications through the designated channel. If the function is disabled, the channel will  not receive any file change notifications. Note that the id and resourceId in the constructed Channel object must be the same as those in the Channel object subscribed through the Changes.subscribe API.

6.2 Development Procedure

Step 1 Call the Drive.Builder.build API to create the Drive object.

  1. private Drive buildDrive() {  
  2.    Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();  
  3.    return service;  
  4. }

Step 2 Obtain the watchId and resourceId cached when your app subscribes to the file change notification function, and call the Channels.stop API to disable sending file change notifications through the designated channel.

  1. /**  
  2. * Stop the designated channel.
  3. * @param context Context
  4. * @param id UUID or similar unique string that identifies this channel. This parameter must be the same as the ID used by the subscribe API.
  5. */  
  6. private void stopChannel(Context context, String id) {  
  7.    try {  
  8.        Drive drive = buildDrive();  
  9.        SharedPreferences preferences = context.getSharedPreferences("channel_config", Context.MODE_PRIVATE);  
  10.        String resourceId = preferences.getString("resourceId", "");  
  11.        Channel channel = new Channel();  
  12.        channel.setId(id);  
  13.        channel.setCategory("api#channel");  
  14.        channel.setResourceId(resourceId);  
  15.        Drive.Channels.Stop stopReq = drive.channels().stop(channel);  
  16.        stopReq.execute();  
  17.    } catch (Exception e) {  
  18.        Log.e(TAG, "stopChannels error: " + e.toString());  
  19.    }  
  20. }
CAUTION:

Call the Channels.stop API in the subthread. The process of stopping file change notification takes a while and requires an Internet connection.

7 Commenting on Files

7.1 Use Case

HUAWEI Drive Kit allows your app to provide file commenting services for users, including commenting on files in the cloud as well as viewing, updating, and deleting comments. 

7.2 Development Procedure

Step 1 Call the Drive.Builder.build API to create the Drive object.

  1. private Drive buildDrive() {
  2.    Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
  3.    return service;
  4. }

Step 2 Call the Comments APIs.

Call the Comments.create to create a comment.

  1. /**
  2. * Create a comment.
  3. *
  4. * @param fileId File ID.
  5. */
  6. private Comment createComments(String fileId) {
  7.    Comment comment = null;
  8.    Drive drive = buildDrive();
  9.    try {
  10.        Comment content = new Comment();
  11.        content.setDescription("interface test");
  12.        content.setCreatedTime(new DateTime(System.currentTimeMillis()));
  13.        comment = drive.comments().create(fileId, content).setFields("*").execute();
  14.    } catch (Exception ex) {
  15.        Log.e(TAG, "createComments error: " + ex.toString());
  16.    }
  17.    return comment;
  18. }

Call the Comments.list API to list comments.

  1. /**
  2. * List comments.
  3. *
  4. * @param fileId File ID.
  5. */
  6. private List<Comment> listComments(String fileId) {
  7.    Drive drive = buildDrive();
  8.    ArrayList<Comment> commentArrayList = new ArrayList<>();
  9.    String nextCursor = null;
  10.    try {
  11.        Drive.Comments.List request = drive.comments().list(fileId);
  12.        do {
  13.            if (nextCursor != null) {
  14.                request.setCursor(nextCursor);
  15.            }
  16.            CommentList commentList = request.setPageSize(100).setFields("*").execute();
  17.            ArrayList<Comment> comments = (ArrayList<Comment>) commentList.getComments();
  18.            if (comments == null) {
  19.                break;
  20.            }
  21.            commentArrayList.addAll(comments);
  22.            nextCursor = commentList.getNextCursor();
  23.        } while (!StringUtils.isNullOrEmpty(nextCursor));
  24.    } catch (IOException e) {
  25.        Logger.e(TAG, "comments list error: " + e.toString());
  26.    }
  27.    return commentArrayList;
  28. }

Call the Comments.get API to retrieve comment details.

  1. /**
  2. * Retrieve comment details.
  3. *
  4. * @param fileId File ID.
  5. * @param commentId Comment ID.
  6. */
  7. private Comment getComments(String fileId, String commentId) {
  8.    Comment comment = null;
  9.    Drive drive = buildDrive();
  10.    try {
  11.        comment = drive.comments().get(fileId, commentId).setFields("*").execute();
  12.        Log.d(TAG, "comment: " + comment.getDescription());
  13.    } catch (Exception ex) {
  14.        Log.e(TAG, "getComments error: " + ex.toString());
  15.    }
  16.    return comment;
  17. }

Call the Comments.update API to update a comment.

  1. /**
  2. * Update a comment.
  3. *
  4. * @param fileId File ID.
  5. * @param commentId Comment ID.
  6. */
  7. private void updateComments(String fileId, String commentId) {
  8.    Drive drive = buildDrive();
  9.    try {
  10.        Comment content = new Comment();
  11.        content.setDescription("update interface test");
  12.        drive.comments().update(fileId, commentId, content).execute();
  13.    } catch (Exception ex) {
  14.        Log.e(TAG, "updateComments error: " + ex.toString());
  15.    }
  16. }

Call the Comments.delete API to delete a comment.

  1. /**
  2. * Delete a comment.
  3. *
  4. * @param fileId File ID.
  5. * @param commentId Comment ID.
  6. */
  7. private void deleteComments(String fileId, String commentId) {
  8.    Drive drive = buildDrive();
  9.    try {
  10.        drive.comments().delete(fileId, commentId).execute();
  11.    } catch (Exception ex) {
  12.        Log.e(TAG, "deleteComments error: " + ex.toString());
  13.    }
  14. }

CAUTION:

Call the Comments APIs in the subthread. File commenting takes a while and requires an Internet connection.

8 Replying to Comments

8.1 Use Case

HUAWEI Drive Kit allows your app to provide the reply function for users, including adding, viewing, updating, and deleting replies to comments on files in the cloud.

8.2 Development Procedure

Step 1 Call the Drive.Builder.build API to create the Drive object.

  1. private Drive buildDrive() {
  2.    Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
  3.    return service;
  4. }

Step 2 Call the Replies APIs. 

Call the Replies.create API to create a reply to a comment.

  1. /**
  2. * Create a reply to a comment.  
  3. *
  4. * @param fileId File ID.
  5. * @param commentId Comment ID.
  6. */
  7. private Reply createReplies(String fileId, String commentId) {
  8.    Reply replyResponse = null;
  9.    Drive drive = buildDrive();
  10.    try {
  11.        Reply reply = new Reply();
  12.        reply.setDescription("interface test reply");
  13.        reply.setOperate("resolve");
  14.        replyResponse = drive.replies().create(fileId, commentId, reply).setFields("*").execute();
  15.    } catch (Exception ex) {
  16.        Log.e(TAG, "createReplies error: " + ex.toString());
  17.    }
  18.    return replyResponse;
  19. }

Call the Replies.list API to list replies to a comment.

  1. /**
  2. * List replies to the comment.
  3. *
  4. * @param fileId File ID.
  5. * @param commentId Comment ID.
  6. */
  7. private List<Reply> listReplies(String fileId, String commentId) {
  8.    Drive drive = buildDrive();
  9.    List<Reply> replyResponse = new ArrayList<>();
  10.    String nextCursor = null;
  11.    try {
  12.        Drive.Replies.List listReq = drive.replies().list(fileId, commentId);
  13.        do {
  14.            if (nextCursor != null) {
  15.                listReq.setCursor(nextCursor);
  16.            }
  17.            ReplyList replyList = listReq.setFields("*").execute();
  18.            List<Reply> replies = replyList.getReplies();
  19.            if (replies == null) {
  20.                break;
  21.            }
  22.            replyResponse.addAll(replies);
  23.            nextCursor = replyList.getNextCursor();
  24.        } while (StringUtils.isNullOrEmpty(nextCursor));
  25.    } catch (Exception ex) {
  26.        Log.e(TAG, "listReplies error: " + ex.toString());
  27.    }
  28.    return replyResponse;
  29. }

Call the Replies.get API to retrieve reply details.

  1. /**
  2. * Retrieve reply details.
  3. *
  4. * @param fileId File ID.
  5. * @param commentId Comment ID.
  6. * @param replyId Reply ID.
  7. */
  8. private Reply getReplies(String fileId, String commentId, String replyId) {
  9.    Reply reply = null;
  10.    Drive drive = buildDrive();
  11.    try {
  12.        reply = drive.replies().get(fileId, commentId, replyId).setFields("*").execute();
  13.    } catch (Exception ex) {
  14.        Log.e(TAG, "getReplies error: " + ex.toString());
  15.    }
  16.    return reply;
  17. }

Call the Replies.update API to update a reply.

  1. /**
  2. * Update a reply.
  3. *
  4. * @param fileId File ID.
  5. * @param commenId Comment ID.
  6. * @param replyId Reply ID.
  7. */
  8. private void updateReplies(String fileId, String commentId, String replyId) {
  9.    Drive drive = buildDrive();
  10.    try {
  11.        Reply reply = new Reply();
  12.        reply.setDescription("interface test reply");
  13.        reply.setOperate("reopen");
  14.        drive.replies().update(fileId, commentId, replyId, reply).execute();
  15.    } catch (Exception ex) {
  16.        Log.e(TAG, "updateReplies error: " + ex.toString());
  17.    }
  18. }

Call the Replies.delete API to delete a reply.

  1. /**
  2. * Delete a reply.
  3. *
  4. * @param fileId File ID.
  5. * @param commenId Comment ID.
  6. * @param replyId Reply ID.
  7. */
  8. private void deleteReplies(String fileId, String commentId, String replyId) {
  9.    Drive drive = buildDrive();
  10.    try {
  11.        drive.replies().delete(fileId, commentId, replyId).execute();
  12.    } catch (Exception ex) {
  13.        Log.e(TAG, "deleteReplies error: " + ex.toString());
  14.    }
  15. }
CAUTION:
Call the Replies APIs in the subthread. The process of replying to a comment takes a while and requires an Internet connection.

9 Performing Batch Operations

9.1 Use Case

HUAWEI Drive Kit allows your app to perform batch operations using an API, including:

9.2 Development Procedure

This section uses the creation of a batch of folders as an example.

Step 1 Call the Drive.Builder.build API to create the Drive object.

  1. private Drive buildDrive() {
  2.    Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
  3.    return service;
  4. }

Step 2 Create the JsonBatchCallback object and call the batch function of Drive to obtain the BatchRequest object. Then, call the queue function of the Files.Create method to add the list of operations you want to execute to the queue, and run BatchRequest.execute.

  1. /**
  2. * Create a batch of callbacks.
  3. */
  4. JsonBatchCallback<File> callback = new JsonBatchCallback<File>() {
  5.    @Override
  6.    public void onFailure(JsonError e, HttpHeaders responseHeaders) throws IOException {
  7.        Logger.i(TAG, "callback error: " + e.toString());
  8.    }
  9.    @Override
  10.    public void onSuccess(File file, HttpHeaders responseHeaders) throws IOException {
  11.        Logger.i(TAG, "callback sucessful: " + file.toString());
  12.    }
  13. };
  14. /**
  15. * Create a batch of folders.
  16. */
  17. private void batchCreateDirectory() {
  18.    Drive drive = buildDrive();
  19.    BatchRequest batch = drive.batch();
  20.    try {
  21.        for (int i = 0; i < 2; i++) {
  22.            Map<String, String> appProperties = new HashMap<>();
  23.            appProperties.put("appProperties", "property");
  24.            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
  25.            String dirName = formatter.format(new Date()) + "_" + i;
  26.            Logger.i(TAG, "executeFilesCreate: " + dirName);
  27.            File file = new File();
  28.            file.setFileName(dirName)
  29.                    .setAppSettings(appProperties)
  30.                    .setMimeType("application/vnd.huawei-apps.folder");
  31.            Drive.Files.Create create = drive.files().create(file);
  32.            create.queue(batch, callback);
  33.        }
  34.        batch.execute();
  35.    } catch (Exception e) {
  36.        Logger.e(TAG, "batchCreateDirectory error: " + e.toString());
  37.    }
  38. }