loading...

Want a simple, secure, and efficient file storage ? Try HUAWEI Cloud Storage Kit

singlebubble1 profile image singlebubble ・10 min read

Alt Text
Huawei Cloud Storage is scalable and maintenance-free. It allows us to store high volumes of data such as images, audios, and videos generated by your users securely and economically with direct device access.

The service is stable, secure, efficient, and easy-to-use, and can free you from development, deployment, O&M, and capacity expansion of storage servers. Developers do not need to pay attention to indicators such as availability, reliability, and durability and can focus on service capability building and operations, improving user experience.

Today in this article we are going to see how to integrate Huawei Cloud Storage kit into your apps.

Prerequisite

  1. Must have a Huawei Developer Account
  2. Must have a Huawei phone with HMS 4.0.0.300 or later
  3. Must have a laptop or desktop with Android Studio , Jdk 1.8, SDK platform 26 and Gradle 4.6 installed. Alt Text

Things Need To Be Done

  1. First we need to create a project in android studio.
  2. Get the SHA Key. For getting the SHA key we can refer to this article.
  3. Create an app in the Huawei app gallery connect.
  4. Enable Auth Service, Account kit and Cloud Storage setting in Manage APIs section.
  5. Provide the SHA Key in App Information Section.
  6. Provide storage location.
  7. Go to Auth Service and enable Huawei Account and Anonymous account.
  8. After Cloud Storage is enabled, go to My projects --> Project Setting --> General Information and download and open the agconnect-services.json file when integrating the Cloud Storage SDK of AppGallery Connect, and add storage-related content to the service tag.

    Example:
    "cloudstorage": {
    "storage_url": "",
    "default_bucket": ""
    }

    a) We can select China for Data storage location. In this way, set storage_url:
    https://agc-storage-drcn.platform.dbankcloud.cn.

    We can select Singapore for Data storage location. In this way, set storage_url:
    https://ops-dra.agcstorage.link.

    We can select Germany for Data storage location. In this way, set storage_url:
    https://ops-dre.agcstorage.link.

    b) The value of default_bucket is the information entered in the storage instance box on the Project Setting --> Build --> Cloud Storage page, as shown in the following figure.

    After providing the information in agconnect-services.json file, copy and paste the file inside app folder of android project.

  9. Copy and paste the below maven url inside the repositories of buildscript and allprojects (project build.gradle file):
    maven { url 'http://developer.huawei.com/repo/' }

  10. Copy and paste the below classpath inside the dependencies of buildscript ( project build.gradle file ):
    classpath 'com.huawei.agconnect:agcp:1.3.1.300'

  11. Copy and paste the below plugin in the app build.gradle file:
    apply plugin: 'com.huawei.agconnect'

  12. Copy and paste the below libraries inside the dependencies of app build.gradle file:
    implementation 'com.huawei.agconnect:agconnect-core:1.3.1.300'
    implementation 'com.huawei.agconnect:agconnect-auth:1.3.1.300'
    implementation "com.huawei.agconnect:agconnect-storage:1.3.0.92"
    implementation 'com.huawei.hms:hwid:4.0.1.301'

  13. Add below Permission in Android Manifest file:




  14. Now sync the gradle.

Demo

Alt Text
Alt Text

Let’s Code

Development process of Huawei Cloud Storage are as follows:
1)Integrate the Auth Service SDK
2)Enable Cloud Storage
3)Initialize Cloud Storage
4)Manage files

Integrate the Auth Service SDK

Cloud Storage depends on Auth Service. We need to integrate the Auth Service SDK in advance. After completing “Things Need To Be Done”, we have already implemented the Auth Service SDK and HMS Account Kit SDK in our app. Now we have to use it in our code. Here we will choose two ways to authenticate user:

1) Using IdToken SignIn, we will allow user to Sign In the app. For example, if user by mistake Sign Out from the app, he/she can easily SignIn using this functionality.

private void idTokenSignIn() {

     mHuaweiIdAuthParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
             .setIdToken()
             .setAccessToken()
             .setProfile()
             .createParams();
     service = HuaweiIdAuthManager.getService(MainActivity.this, mHuaweiIdAuthParams);
     startActivityForResult(service.getSignInIntent(), Constant.REQUEST_SIGN_IN_LOGIN);
 }

Once we wrote the above code, we can achieve the result using below code:

if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN) {
     Task<AuthHuaweiId> authHuaweiIdTask;
     AuthHuaweiId huaweiAccount;
     authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
     if (authHuaweiIdTask.isSuccessful()) {

         huaweiAccount = authHuaweiIdTask.getResult();
         displayInfo(huaweiAccount,null);
         Log.e("AGC", "HMS signIn Success");
         Log.e("AGC", "accessToken:" + huaweiAccount.getAccessToken());
         AGConnectAuthCredential credential = HwIdAuthProvider.credentialWithToken(huaweiAccount.getAccessToken());
         AGConnectAuth.getInstance().signIn(credential).addOnSuccessListener(new OnSuccessListener<SignInResult>() {
             @Override
             public void onSuccess(SignInResult signInResult) {

                 printUserInfo();
             }
         }).addOnFailureListener(new OnFailureListener() {
             @Override
             public void onFailure(Exception e) {
                 Log.e("AGC", "AGC Auth Error: " + e.getMessage());
             }
         });
         Toast.makeText(MainActivity.this, huaweiAccount.getDisplayName() + " signIn success ", Toast.LENGTH_LONG).show();
         // printUserInfo();

     } else {
         Toast.makeText(MainActivity.this, getString(R.string.sign_in_failed) + ((ApiException) authHuaweiIdTask.getException()).getStatusCode(), Toast.LENGTH_LONG).show();
     }
 }

To know more about HMS Account Kit, follow this article.

2) Using AGConnectUser, we will check whether the user is already signed in or not.

AGConnectUser currentUser = AGConnectAuth.getInstance().getCurrentUser();
 if(currentUser != null){
     displayInfo(null,currentUser);
     getFileList();
 }

3) Since we are using both ways to determine the user SignIn process, we need to check both scenarios in order to sign out user from the app.

public void signOut(View view){
     if(service!=null){
         Task<Void> signOutTask = service.signOut();

         signOutTask.addOnCompleteListener(new OnCompleteListener<Void>() {
             @Override
             public void onComplete(Task<Void> task) {
                 Toast.makeText(MainActivity.this, R.string.sign_out_completely, Toast.LENGTH_LONG).show();
                 clearInfo();
             }

         }).addOnFailureListener(new OnFailureListener() {
             @Override
             public void onFailure(Exception e) {
                 System.out.println("Exception " + e);
             }
         });
     }else if (currentUser != null) {
         AGConnectAuth.getInstance().signOut();
         Toast.makeText(MainActivity.this, R.string.sign_out_completely, Toast.LENGTH_LONG).show();
         clearInfo();
     }
 }

NOTE: Do not forget to initialize AGConnectInstance in onCreate method of Activity class.

AGConnectInstance.initialize(this);

Enable Cloud Storage

This service is not enabled by default, and we need to manually enable Cloud Storage in AppGallery Connect if required. In order to manually enable the service, we need to select the project first in AGC and then go to My Project à Build à Cloud Storage. The Cloud Storage page is displayed. If it is the first time that we are using Cloud Storage, click Enable now in the upper right corner.
Alt Text
After enabling the cloud storage it will look something like this:
Alt Text

A) Storage Instance: Also known as Bucket of Cloud Storage, is where we store our files inside the folder or if we want we can also store our files without creating any folder. It acts as a container, which contains files and files could be an image, video or documents. We can create many storage instance but we need to be paid developer in order to create our own bucket. For practice purpose we will be using our default storage instance or bucket.

B) Upload File: We can upload our files from our PC by clicking this button.

C) New Folder: We can create new folders or sub folders by clicking this button. It will ask the name of the folder and after that select submit button in order to create it.
Alt Text
Alt Text

D) Operation: In operation we will find two buttons i.e. Delete and Details. As the name implies, delete will remove the files or folders from cloud storage and details will provide information about the files.
Alt Text
Alt Text

Initialize Cloud Storage

Before using Cloud Storage on the app client, initialize this service and specify the storage instance used by the client. In order to do that we need to call AGCStorageManagement.getInstance method to initialize the service.

  • If we only need to initialize the default storage instance:
AGCStorageManagement storageManagement = AGCStorageManagement.getInstance();
  • When we create our own storage instance:
AGCStorageManagement storageManagement = AGCStorageManagement.getInstance("custom-bucket-name");

Also make sure to declare it in onCreate Method of the Activity class.

Manage files

After you complete cloud storage instance initialization, we can use the Cloud Storage SDK to upload, download, show file list, delete files and show details of file using metadata in our app.

UPLOAD A FILE

Cloud Storage allows you to quickly upload directories and files on local devices to the cloud server of AppGallery Connect. In order to do that we need to first create a StorageReference using AGCStorageManagement and then use that reference to upload files from app to our Huawei Cloud Storage. Below is the code to upload file from app to cloud storage:

private void uploadFile() {
     String files = "";
     if (curFileName.toLowerCase().endsWith(".docx") || curFileName.toLowerCase().endsWith(".doc") ) {
         files = "DOCS/";
     } else if (curFileName.toLowerCase().endsWith("jpg") || curFileName.toLowerCase().endsWith(".png")) {
         files = "IMAGES/";
     } else if (curFileName.toLowerCase().endsWith("xlsx") || curFileName.toLowerCase().endsWith(".xls")) {
         files = "EXCELS/";
     }else if (curFileName.toLowerCase().endsWith("mp4")) {
         files = "VIDEOS/";
     }
     StorageReference reference = storageManagement.getStorageReference(files + curFileName);
     File filePath = new File(curFilePath + "/" + curFileName);
     if (filePath.isFile()) {
         UploadTask task = reference.putFile(filePath);
         task.addOnFailureListener(new OnFailureListener() {
             @Override
             public void onFailure(Exception ex) {
                 Log.e("MainActivity", ex.getMessage());
                 progressDialog.dismiss();
             }

         }).addOnSuccessListener(new OnSuccessListener<UploadTask.UploadResult>() {
             @Override
             public void onSuccess(UploadTask.UploadResult uploadResult) {
                 Log.i("MainActivity", uploadResult.toString());
                 progressDialog.dismiss();
             }
         }).addOnProgressListener(new OnProgressListener<UploadTask.UploadResult>() {
             @Override
             public void onProgress(UploadTask.UploadResult uploadResult) {
                 System.out.println(String.format("progress: %f", (uploadResult.getBytesTransferred() * 1.0) / uploadResult.getTotalByteCount()));
             }
         }).addOnPausedListener(new OnPausedListener<UploadTask.UploadResult>() {
             @Override
             public void onPaused(UploadTask.UploadResult uploadResult) {

             }
         });

     }
 }

In the app, we select files using file browser and then we use this function to upload file on cloud storage. Here curFilePath contains the path of the local device file and curFileName contains the name of the local file.

LISTING FILES

The Cloud Storage SDK allows you to list all files or subdirectories in a directory on the cloud by calling APIs. In order to do that we need to first create a StorageReference using AGCStorageManagement and then use that reference to get all files including directories from Huawei Cloud Storage to our app and store it in a HashMap or List whatever suits us. Below is the code to get all the files from cloud storage as a list:

public void getFileList() {
     progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading the list...");
     expandableStorageList.clear();
     if (storageManagement == null) {
         storageManagement = AGCStorageManagement.getInstance();
     }
     new Thread(new Runnable() {
         @Override
         public void run() {
             StorageReference dirReference = storageManagement.getStorageReference();
             Task<ListResult> dirResultTask = dirReference.listAll();
             try {
                 ListResult dirResult = Tasks.await(dirResultTask);
                 List<StorageReference> dirList = dirResult.getDirList();

                 for (int i = 0; i < dirList.size(); i++) {
                     System.out.println("DIR List " + i + ":" + dirList.get(i).getPath());
                     StorageReference fileStorageRef = storageManagement.getStorageReference(dirList.get(i).getPath());
                     List<String> fileStorageList = new ArrayList<>();
                     Task<ListResult> fileResultTask = fileStorageRef.listAll();
                     ListResult fileResult = Tasks.await(fileResultTask);
                     List<StorageReference> fileList = fileResult.getFileList();
                     for (int j = 0; j < fileList.size(); j++) {
                         System.out.println("FILE List " + j + ":" + fileList.get(j).getName());
                         if (!fileList.get(j).getName().isEmpty() && fileList.get(j).getName() != null) {
                             fileStorageList.add(fileList.get(j).getName());
                         }
                     }
                     expandableStorageList.put(dirList.get(i).getPath(), fileStorageList);
                 }

                 runOnUiThread(new Runnable() {
                     public void run() {
                         progressDialog.dismiss();
                         Intent intent = new Intent(MainActivity.this, ShowListActivity.class);
                         intent.putExtra("map", expandableStorageList);
                         startActivity(intent);
                         finish();
                     }
                 });

             } catch (Exception e) {
                 e.printStackTrace();

             } finally {

             }
         }
     }).start();
 }

In the above code expandableStorageList is the Hash Map which stores the list of all files as values and directory as key.
Alt Text

SHOW DETAILS OF A FILE

After a file is saved to the cloud, you can obtain the metadata (details) of the file to determine whether to download the file. In order to achieve details of file we will call the StorageReference.getFileMetadata method to obtain the FileMetadata instance that contains the file metadata. Below is the code to achieve file metadata or in other words file details:

private void fileInfo(String group, String expandedListText) {
     if (storageManagement == null) {
         storageManagement = AGCStorageManagement.getInstance();
     }
     AGConnectUser currentUser = AGConnectAuth.getInstance().getCurrentUser();
     if (currentUser != null) {
         Log.i("AGC", "deleteFile...DisplayName:" + currentUser.getDisplayName() + " ,userId=" + currentUser.getUid());
     } else {
         Log.e("AGC", "deleteFile...User Null");
     }

     new Thread(new Runnable() {
         @Override
         public void run() {
             try {
                 StorageReference storageReference = storageManagement.getStorageReference(group.trim() + expandedListText);
                 Task<FileMetadata> metaTask = storageReference.getFileMetadata();
                 FileMetadata metadata = null;
                 metadata = Tasks.await(metaTask);
                 size = String.valueOf(metadata.getSize());
                 contentType = metadata.getContentType();
                 ((Activity) context).runOnUiThread(new Runnable() {
                     public void run() {                         // GIVE YOUR LOGIC HERE …
                     }
                 });
             } catch (ExecutionException e) {
                 e.printStackTrace();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     }).start();
 }

Alt Text

DOWNLOAD A FILE

After files are uploaded to the cloud, you can call the Cloud Storage SDK to download files on the cloud to the local device. In order to download file, we will call the StorageReference.getFile method to write the file data on the cloud to the local file. Below is the code to download file from cloud storage to local device:

private void downloadFile(String group, String expandedListText) {
     new Thread(new Runnable() {
         @Override
         public void run() {
             StorageReference reference = storageManagement.getStorageReference(group + expandedListText);
             String path = getAGCSdkDirPath();
             // Toast.makeText(MainActivity.this,path,Toast.LENGTH_LONG).show();
             String sufix = "";
             if (expandedListText.toLowerCase().endsWith(".docx")) {
                 sufix = ".docx";
             } else if (expandedListText.toLowerCase().endsWith(".doc")) {
                 sufix = ".docx";
             } else if (expandedListText.toLowerCase().endsWith("jpg")) {
                 sufix = ".jpg";
             } else if (expandedListText.toLowerCase().endsWith(".png")) {
                 sufix = ".png";
             } else if (expandedListText.toLowerCase().endsWith("xlsx")) {
                 sufix = ".xlsx";
             } else if (expandedListText.toLowerCase().endsWith("xls")) {
                 sufix = ".xls";
             } else if (expandedListText.toLowerCase().endsWith("mp4")) {
                 sufix = ".mp4";
             }
             File filePath = new File(path + expandedListText.replace(sufix, "").trim() + SystemClock.currentThreadTimeMillis() + sufix);

             DownloadTask task = reference.getFile(filePath);
             task.addOnFailureListener(new OnFailureListener() {
                 @Override
                 public void onFailure(Exception e) {
                     // Provide Your Logic Here...
                 }
             }).addOnSuccessListener(new OnSuccessListener<DownloadTask.DownloadResult>() {
                 @Override
                 public void onSuccess(DownloadTask.DownloadResult downloadResult) {
                     // Provide Your Logic Here...
                 }
             });
         }
     }).start();
 }

Alt Text

DELETE A FILE

We can call the Cloud Storage SDK to delete unnecessary files from the cloud on the app client. In order to delete a file from app, we need to Call StorageReference.delete to delete a file on the cloud. Below is the code to delete file from cloud storage using our app:

private void deleteFile(String group, String expandedListText) {
     if (storageManagement == null) {
         storageManagement = AGCStorageManagement.getInstance();
     }
     AGConnectUser currentUser = AGConnectAuth.getInstance().getCurrentUser();
     if (currentUser != null) {
         Log.i("AGC", "deleteFile...DisplayName:" + currentUser.getDisplayName() + " ,userId=" + currentUser.getUid());
     } else {
         Log.e("AGC", "deleteFile...User Null");
     }

     new Thread(new Runnable() {
         @Override
         public void run() {
             StorageReference storageReference = storageManagement.getStorageReference(group.trim() + expandedListText);
             Task<Void> deleteTask = storageReference.delete();
             deleteTask.addOnCompleteListener(new OnCompleteListener<Void>() {
                 @Override
                 public void onComplete(Task<Void> task) {
                     ((Activity) context).runOnUiThread(new Runnable() {
                         public void run() {
                            // Provide Your Logic Here...
                         }
                     });
                 }
             }).addOnFailureListener(new OnFailureListener() {
                 @Override
                 public void onFailure(Exception e) {
                     ((Activity) context).runOnUiThread(new Runnable() {
                         public void run() {
                           // Provide Your Logic Here...
                         }
                     });
                 }
             });

         }
     }).start();
 }

Alt Text

GitHub Link

https://github.com/DTSE-India-Community/Huawei-Cloud-Storage

For More Information

1) https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-cloudstorage-introduction
2) https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201206040914750083&fid=0101187876626530001

HAPPY CODING :)

Posted on by:

singlebubble1 profile

singlebubble

@singlebubble1

live, laough and love coding, cooking and skiing

Discussion

markdown guide