Introduction

Cloud Storage is scalable and maintenance-free. By integrating the Cloud Storage SDK, you can store high volumes of data such as images, audios, and videos generated by your users to the cloud or download these data from the cloud.

What You Will Create

In this codelab, you will build an app that integrates Cloud Storage capabilities. Your app will allow users to upload a file to the cloud and download it to a local path by calling APIs.

What You Will Learn

Development Environment and Skill Requirements

Device Requirements

To integrate Cloud Storage of AppGallery Connect, you must complete the following preparations:

For details, please refer to Configuring App Information in AppGallery Connect.

Enabling Cloud Storage

Before integrating the Cloud Storage SDK, you need to enable Cloud Storage in AppGallery Connect.

  1. Sign in to AppGallery Connect and click My projects.
  2. Click the project for which you need to enable Cloud Storage.
  3. Go to Build > Cloud Storage. The Cloud Storage page is displayed. Click Enable now in the upper right corner.
  4. On the page displayed, set Storage instance and Data storage location.
  5. Click Next. The Define security rules page is displayed by default.
  6. Click Finish. Cloud Storage is successfully enabled for the project.

Integrating the Cloud Storage SDK

If you are using Android Studio, you need to integrate the Cloud Storage SDK into your Android Studio project before development.

  1. Sign in to AppGallery Connect and click My projects.
  2. Find and click your project.
  3. Go to Project Setting > General information, and click agconnect-services.json under App information to download the configuration file.
  4. Copy the agconnect-services.json file to the app's root directory of your Android Studio project.
  5. Open the app-level build.gradle file and add the following code to integrate the Cloud Storage SDK:
    dependencies { // Configure the following address. // Add the dependency on the AppGallery Connect framework first. implementation 'com.huawei.agconnect:agconnect-storage:1.3.1.100' }
  6. Click Sync Now to synchronize the configuration.
  1. Create a page in your Android Studio project, with six buttons and a textview required.
    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical" tools:context=".MainActivity"> <Button android:onClick="uploadFile" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAllCaps="false" android:text="Upload File" /> <Button android:onClick="downloadFile" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAllCaps="false" android:text="Download File" /> <Button android:onClick="getFileMetadata" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAllCaps="false" android:text="Get FileMetadata" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="updateFileMetadata" android:text="get DownloadUrl" android:textAllCaps="false" /> <Button android:onClick="getFileList" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAllCaps="false" android:text="Get FileList" /> <Button android:onClick="deleteFile" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAllCaps="false" android:text="Delete File" /> <TextView android:id="@+id/showResult" android:enabled="false" android:hint="This will display the result of the operation" android:layout_width="match_parent" android:layout_marginTop="10dp" android:gravity="center" android:layout_height="wrap_content" /> </LinearLayout>
  2. Add six buttons and a textview. The functions of the buttons and textview are as follows:
    • Button for uploading files
    • Button for downloading files
    • Button for obtaining object metadata
    • Button for updating object metadata
    • Button for obtaining the object list
    • Button for deleting files
    • Display the result obtained by tapping the preceding buttons.
  3. Design the page layout as follows.

The sample code in this codelab uses the anonymous sign-in mode. Therefore, you need to enable the anonymous account authentication mode of Auth Service in AppGallery Connect. Otherwise, the sign-in fails.

  1. Sign in to AppGallery Connect and click My projects.
  2. Find and click your project.
  3. Go to Build > Auth Service. If it is the first time that you use Auth Service, click Enable now in the upper right corner.
  4. Click the Authentication mode tab and click Enable in the Operation column for Anonymous account.
  5. Add the following build dependencies to the app-level build.gradle file (usually in the app directory) to integrate Auth Service:
    implementation 'com.huawei.agconnect:agconnect-core:1.4.1.300' implementation 'com.huawei.agconnect:agconnect-auth:1.4.1.300'
  6. Add permissions to the AndroidManifest.xml file.
    <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  7. Call the method for permission application in OnCreate of MainActivity. The sample code is as follows:
    private String[] permissions = { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, }; ActivityCompat.requestPermissions(this, permissions, 1);
  8. Call the required Auth Service method in OnCreate of MainActivity. You need to ensure that the anonymous account sign-in function can work properly before verifying Cloud Storage functions. The sample code for the anonymous account authentication mode is as follows:
    private void login() { if (AGConnectAuth.getInstance().getCurrentUser() != null) { System.out.println("already sign a user"); return; } AGConnectAuth.getInstance().signInAnonymously().addOnSuccessListener(signInResult -> System.out.println("AGConnect OnSuccess")) .addOnFailureListener(e -> System.out.println("AGConnect OnFail: " + e.getMessage())); }

You can call related APIs of the Cloud Storage SDK to develop functions.

Initializing the Storage Instance

Call the AGCStorageManagement.getInstance API to initialize the storage instance before your client uses any Cloud Storage functions.

private void initAGCStorageManagement() { mAGCStorageManagement = AGCStorageManagement.getInstance(); }

File Upload

Tap Upload File. The uploadFile method is called to upload a file to the cloud server.

private void uploadFile() { final String path = "test.jpg"; String fileName = "test.jpg"; String agcSdkDirPath = getAGCSdkDirPath(); final File file = new File(agcSdkDirPath, fileName); if (!file.exists()) { mShowResultTv.setText("file is not exist!"); return; } new Thread(new Runnable() { @Override public void run() { StorageReference storageReference = mAGCStorageManagement.getStorageReference(path); UploadTask uploadTask = storageReference.putFile(file); try { uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.UploadResult>() { @Override public void onSuccess(UploadTask.UploadResult uploadResult) { mShowResultTv.setText("upload success!"); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { mShowResultTv.setText("upload failure!"); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); }

(The file to be uploaded is configured in the project code, namely, the test.jpg file in the AGCSDK directory of the test mobile phone.)

File Download

Tap Download File. The downloadFile method is called to download the file just uploaded from the cloud server to a local path. The file is saved in the upload directory in the download_{*timestamp*}.jpg format.

private void downloadFile() { String fileName = "download_" + System.currentTimeMillis() + ".jpg"; final String path = "test.jpg"; String agcSdkDirPath = getAGCSdkDirPath(); final File file = new File(agcSdkDirPath, fileName); new Thread(new Runnable() { @Override public void run() { StorageReference storageReference = mAGCStorageManagement.getStorageReference(path); DownloadTask downloadTask = storageReference.getFile(file); try { downloadTask.addOnSuccessListener(new OnSuccessListener<DownloadTask.DownloadResult>() { @Override public void onSuccess(DownloadTask.DownloadResult downloadResult) { mShowResultTv.setText("download success!"); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { mShowResultTv.setText("download failure!"); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); }

File Metadata Operations

  1. Tap Get FileMetadata. The getFileMetadata method is called to obtain the file metadata.
    private void getFileMetadata() { final String path = "test.jpg"; new Thread(new Runnable() { @Override public void run() { StorageReference storageReference = mAGCStorageManagement.getStorageReference(path); Task<FileMetadata> fileMetadataTask = storageReference.getFileMetadata(); try { fileMetadataTask.addOnSuccessListener(new OnSuccessListener<FileMetadata>() { @Override public void onSuccess(FileMetadata metadata) { mShowResultTv.setText("getfilemetadata success!"); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { mShowResultTv.setText("getfilemetadata failure!"); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); }
  2. Tap Update FileMetadata. The updateFileMetadata method is called to modify the file metadata.
    private void updateFileMetadata() { final String path = "test.jpg"; new Thread(new Runnable() { @Override public void run() { FileMetadata fileMetadata = initFileMetadata(); StorageReference storageReference = mAGCStorageManagement.getStorageReference(path); Task<FileMetadata> fileMetadataTask = storageReference.updateFileMetadata(fileMetadata); try { fileMetadataTask.addOnSuccessListener(new OnSuccessListener<FileMetadata>() { @Override public void onSuccess(FileMetadata metadata) { mShowResultTv.setText("updatefilemetadata success!"); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { mShowResultTv.setText("updatefilemetadata failure!"); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); }

File List Obtaining

Tap Get FileList. The getFileList method is called to obtain the file list from the cloud server.

private void getFileList() { final String path = "test.jpg"; new Thread(new Runnable() { @Override public void run() { StorageReference storageReference = mAGCStorageManagement.getStorageReference(path); Task<ListResult> listResultTask = null; listResultTask = storageReference.list(100); try { listResultTask.addOnSuccessListener(new OnSuccessListener<ListResult>() { @Override public void onSuccess(ListResult listResult) { mShowResultTv.setText("getfilelist success!"); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { mShowResultTv.setText("getfilelist failure!"); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); }

File Deletion

Tap Delete File. The deleteFile method is called to delete the uploaded file from the cloud server.

private void deleteFile() { final String path = "test.jpg"; System.out.println(String.format("path=%s", path)); new Thread(new Runnable() { @Override public void run() { StorageReference storageReference = mAGCStorageManagement.getStorageReference(path); Task<Void> deleteTask = storageReference.delete(); try { deleteTask.addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mShowResultTv.setText("delete success!"); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { mShowResultTv.setText("delete failure!"); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); }
  1. Relevant methods in OnCreate are as follows:
    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mShowResultTv = findViewById(R.id.showResult); AGConnectInstance.initialize(getApplicationContext()); login(); ActivityCompat.requestPermissions(this, permissions, 1); }
  2. initFileMetadata method for initializing metadata:
    private FileMetadata initFileMetadata() { FileMetadata metadata = new FileMetadata(); metadata.setContentType("image/*"); metadata.setCacheControl("no-cache"); metadata.setContentEncoding("identity"); metadata.setContentDisposition("inline"); metadata.setContentLanguage("en"); return metadata; }
  3. getAGCSdkDirPath method for obtaining a file path:
    private String getAGCSdkDirPath() { String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/AGCSdk/"; System.out.println("path=" + path); File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } return path; }

Cloud Storage of AppGallery Connect provides visualized file management and data analysis functions.

  1. Sign in to AppGallery Connect and click My projects.
  2. Find and click your project.
  3. Go to Build > Cloud Storage. On the Cloud Storage page that is displayed, you can manage files, including uploading, viewing, downloading, and deleting files.
  4. Click the Usage tab to view data analysis of Cloud Storage. The page displays the storage usage, number of storage objects, network traffic, and number of requests of the current storage instance. You can select a time segment (current day, yesterday, last 7 days, or last 30 days) in the upper right corner of the page.

Well done. You have successfully built an app that integrates Cloud Storage of AppGallery Connect and learned how to manage Cloud Storage usage in AppGallery Connect.

For details about APIs related to Cloud Storage of AppGallery Connect, please refer to API Reference.
Download the demo source code used in this codelab from the following address:

Download source code

Code copied