Introduction

Cloud Functions enables serverless computing. It provides the Function as a Service (FaaS) capabilities to simplify app development and O&M so your functions can be implemented more easily and your service capabilities can be built more quickly.

  1. Cloud Functions provides an efficient and reliable framework for developing and running functions. It frees you from complex traditional development and O&M of apps. Server configuration and management, code deployment, load balancing, autoscaling, and high reliability assurance are now streamlined. You only need to focus on service logic and function code to build reliable and scalable serverless apps.
  2. As the core of serverless computing, Cloud Functions works with other cloud services like building blocks to implement your service logic.

What You Will Create

In this codelab, you will build a function that can use Cloud Functions to interact with the client. The process includes:

What You Will Learn

Development Environment and Skill Requirements

Device Requirements

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

For details, please refer to Preparations for Integrating HUAWEI AppGallery Connect.

Creating a Cloud Function

  1. Sign in to AppGallery Connect and click My projects. Click the app for which you want to enable Cloud Functions on the project card, and go to Build > Cloud Functions. If it is the first time that you use Cloud Functions, click Enable now in the upper right corner.
  2. If the data storage location is not set, you need to set it for your app. For details, please refer to Setting a Data Storage Location.

Integrating the SDK

If you are using Android Studio, you can integrate the Cloud Functions SDK by using the Maven repository into your Android Studio project before development.

  1. Click My projects in AppGallery Connect and find the app for which you want to enable Cloud Functions on the project card.
  2. Go to Project Settings > General information, and click agconnect-services.json to download the configuration file.
  3. Copy the agconnect-services.json file to the app's root directory of your Android Studio project.
  4. Open the app-level build.gradle file and add the following code to integrate the Cloud Functions SDK:
    // Configure the following address: apply plugin: 'com.huawei.agconnect' dependencies { // Configure the following address: implementation 'com.huawei.agconnect:agconnect-function:1.4.1.300' }
  5. Click Sync Now to synchronize the configuration.

Creating a Cloud Function

1. Sign in to AppGallery Connect and click My projects. Click your app on the project card, and go to Build > Cloud Functions.
2. Click New Function on the Functions page.

3. Define the function on the page that is displayed.
a) Enter a function name and description in Name and Description, respectively.
b) Set Code Input Type to Edit code inline.
c) Enter the deployment information in Deployment Information. You can retain the default value.

4. Add the following code to the handler.js file:

let myHandler = function(event, context, callback, logger) { var res = new context.HTTPResponse(context.env, { "res-type": "context.env", "faas-content-type": "json", }, "application/json", "200"); var year; if (event.body) { var _body = JSON.parse(event.body); year = _body.year; } else { year = event.year; } var body = { result:'' }; body.result = animal(year); res.body = body; context.callback(res); function animal(inputYear) { var resultString; if(!isNumber(inputYear)){ resultString = "input is not a number"; }else{ var remainder = inputYear%12; switch (remainder) { case 0: resultString = "Monkey"; break; case 1: resultString = "Chicken"; break; case 2: resultString = "Dog"; break; case 3: resultString = "Pig"; break; case 4: resultString = "Mouse"; break; case 5: resultString = "Cow"; break; case 6: resultString = "Tiger"; break; case 7: resultString = "Rabbit"; break; case 8: resultString = "Dragon"; break; case 9: resultString = "Snake"; break; case 10: resultString = "Horse"; break; case 11: resultString = "Sheep"; break; default: resultString = "No symbolic Animal"; } } return resultString; } function isNumber(input){ if (parseInt(input).toString == "NaN") { return false; } else { return true; } } }; module.exports.myHandler = myHandler;

Testing the Function

1. You can go to the function test page in either of the following ways:

2. Select the new function and version. Enter the following code in the event:

{ "year": 2020 }

3. Check whether the command output is the same as the following:

Adding a Trigger

  1. Click the name of a function in the function list to go to the function details page. If you click the function alias, the page for configuring the function alias will be displayed.
  2. Click Add Trigger on the Configure tab page. The page for adding a trigger is displayed.
  3. Set Trigger Type to HTTP and Method to POST.
  4. Click add and then Save.
  5. Save the last part of Trigger URL under Details for subsequent client requests.

In this codelab, you will create a layout UI shown in the following figure in your Android Studio project. The layout UI must allow you to enter a year and then display the result.
For details about the UI layout, please refer to the following code in the activity_main.xml file:

<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.4"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/instruction"/> <EditText android:id="@+id/year_text" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> <TextView android:id="@+id/rst_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/instruction_result" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.6"/> <Button android:id="@+id/rst_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/OK_button" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.7"/>
  1. Obtain the control instance and set the button tap event in the onCreate method on the app main page.
    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); resultBtn = findViewById(R.id.rst_btn); resultText = findViewById(R.id.rst_text); inputYear = findViewById(R.id.year_text); resultBtn.setOnClickListener(new ButtonClickListener()); }
  2. In the button tap event, obtain the input value in the text box, check whether the value is empty, and verify the value.
    String inputText = inputYear.getText().toString(); if (inputText.equals("") || !isInputLegit(inputText)){ resultText.setText(R.string.year_error); return; }
  3. IsInputLegit method:

    private boolean isInputLegit(String input){ for (int i = 0; i < input.length(); i++){ System.out.println(input.charAt(i)); if (!Character.isDigit(input.charAt(i))){ return false; } } return true; }
  4. Initialize Cloud Functions.
    AGConnectFunction function = AGConnectFunction.getInstance();
  5. Generate a map object of the event required by Cloud Functions. Here, the event key is set to year in the cloud function, and the key of map is set to year accordingly.
    HashMap<String, String> map = new HashMap<>(); map.put("year", inputText);
  6. Call the wrap method in the Cloud Functions SDK to specify a trigger. Use the call method to pass map of the event as a parameter, send the HTTP request of the event, and use Cloud Functions for calculation. Add the callback of the request to receive the result returned by Cloud Functions and display the result in Textview.
    function.wrap("symbolic-animals-$latest").call(map) .addOnCompleteListener(new OnCompleteListener<FunctionResult>() { @Override public void onComplete(Task<FunctionResult> task) { if (task.isSuccessful()){ String value = task.getResult().getValue(); try { JSONObject object = new JSONObject(value); String result = (String)object.get("result"); resultText.setText(result); } catch (JSONException e) { e.printStackTrace(); } Log.i(TAG, value); } else { Exception e = task.getException(); if (e instanceof AGCFunctionException){ AGCFunctionException functionException = (AGCFunctionException)e; int errCode = functionException.getCode(); String message = functionException.getMessage(); Log.e(TAG, "errorCode: " + errCode + ", message: " + message); } } } });
  1. Run your Android Studio project and generate an APK. Then, install the APK on your mobile phone for testing.
  2. Enter a year in the text box and check whether the zodiac sign of the year is displayed on the page.

Well done. You have successfully built your first app that integrates Cloud Functions and learned how to:

To download the sample code, please click the button below:

Download

Code copied