Background
Given the sheer number of apps out there, it's important to make your own app stand out from the crowd. Custom ringtones are a good way to do that, for example, if you've developed a payment, online education, or video app. When a tone is played to indicate a message has been delivered, users will be able to identify your app in an instant, and develop a greater appreciation for it.
So, let's move on to the process for creating custom ringtones in HUAWEI Push Kit to increase your message impressions.
Basic Ideas
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Procedure
1. Set a ringtone for the service and communication messaging channel.
Restrictions: Make sure that the EMUI version is 9.1.0 or later and the Push Service app version is 9.1.1 or later.
To view the Push Service app version, go to Settings > Apps > Apps on your device, and search for Push Service.
1) Perform configuration on your app.
a. The ringtone to be used can only be stored in the /res/raw directory of the app.
b. Supported ringtone file formats are: MP3, WAV, and MPEG.
For example, store the bell.mp3 file in /res/raw.
2) Perform configuration on your app server.
a. Construct a common downlink message request. In the request:
b. Set importance to NORMAL, indicating that the message is a service and communication message.
c. Set default_sound to false, indicating that the value of sound is used.
d. Set sound to the path where the custom ringtone is stored on the app.
For example, for the bell.mp3 file on the app, set sound to /raw/bell.
Code:
{
"validate_only": false,
"message": {
"android": {
"notification": {
"importance": "NORMAL",
"title": "Test ringtone",
"body": "Ringtone bell for this message",
"click_action": {
"type": 3
},
"default_sound": false,
"sound": "/raw/bell"
}
},
"token": [
"xxx"
]
}
}
3) Effects
4) FAQs
a. Q: Why can I only set the ringtone for the service and communication messaging channel?
A: For the other channel, that is, news and marketing messaging channel, the default message reminder mode is no lock screen, no ringtone, and no vibration. Therefore, the ringtone will not take effect even if it is set. For news and marketing messages, the user will need to set a ringtone.
b. Q: Why do I need to set the default ringtone before sending a message for the first time after the app is installed?
A: The ringtone is an attribute for the messaging channel. Therefore, the ringtone will only take effect after being set during the channel creation. Once the channel is created, the user will need to manually modify the messaging settings for a channel.
2. Set a ringtone for a custom messaging channel.
Restrictions: Make sure that the EMUI version is 10.0.0 or later and the Push Service app version is 10.0.0 or later.
1) Perform configuration on your app.
a. Save the ringtone file to the /assets or /res/raw directory.
For example, store the bell.mp3 file in /res/raw.
b. Create a messaging channel. (Note: The custom ringtone can only be set when the channel level is NotificationManager.IMPORTANCE_DEFAULT or higher.)
c. Set the ringtone.
For example, create the messaging channel "test" and set the channel ringtone to "/res/raw/bell.mp3".
Code:
createNotificationChannel("test", "Channel 1", NotificationManager.IMPORTANCE_DEFAULT);
private String createNotificationChannel(String channelID, String channelNAME, int level) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(channelID, channelNAME, level);
channel.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bell), Notification.AUDIO_ATTRIBUTES_DEFAULT);
manager.createNotificationChannel(channel);
return channelID;
} else {
return "";
}
}
2) Perform configuration on your app server.
a. Construct a common downlink message request. In the request:
b. Set importance to NORMAL, indicating that the message is a service and communication message.
c. Set channel_id to the ID of the channel created on the app, so that the message can be displayed on the channel.
For example, set channel_id to test.
Code:
{
"validate_only": false,
"message": {
"android": {
"notification": {
"importance": "NORMAL",
"title": "Test ringtone",
"body": "Custom ringtone for the message displayed through the channel test",
"click_action": {
"type": 3
},
"channel_id": "test"
}
},
"token": [
"xxx"
]
}
}
3) Effects
4) FAQs
Q: Why do I need to set importance to NORMAL for the custom channel?
A: For the other channel, that is, news and marketing messaging channel, the default message reminder mode is no lock screen, no ringtone, and no vibration, which will minimize the distraction to users.
Precautions
1. The ringtone set by a user has the highest priority. If the user changes it to another ringtone, the new ringtone will prevail.
2. The following table lists the impact of each field in the downlink message on the ringtone (the intelligent classification is not considered).
Channel Status (Whether the Channel Has Been Created)default_soundsoundimportance
(EMUI 10.0.0 or later)channel_idRingtoneAnyAny valueAny valueLOWAny valueNoneNot createdtrueAny valueNORMALEmptyDefault system ringtoneNot createdfalse/raw/bellNORMALEmptybell.mp3Not createdfalseEmptyNORMALEmptyDefault system ringtoneAnyAny valueAny valueNORMALtestRingtone for the channel "test"CreatedAny valueAny valueNORMALEmptyRingtone for the original channel, which has not been changedCreatedAny valueAny valueNORMALtestRingtone for the original channel "test", which has not been changed
To learn more, please visit:
HUAWEI Developers official website
Development Guide
Reddit to join developer discussions
GitHub or Gitee to download the demo and sample code
Stack Overflow to solve integration problems
Follow our official account for the latest HMS Core-related news and updates.
Original Source
Related
More information like this, you can visit HUAWEI Developer Forum
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Huawei Push Kit is a messaging service provided by Huawei for developers. It establishes a communication channel between the cloud and devices. Using HMS Push Kit, developers can send the latest messages to users. This helps developers to maintain closer ties with users and increases user awareness, and activity.
User can tap the message displayed in the notification bar of the device and can open the corresponding app, and view more details.
HMS Push Kit is already available for more than 200+ countries and regions. It offers the capacity of sending 10 million messages per second from the server, delivering 99% of them and providing real time push reports, ultimately helping to improve the DAU of your apps.
In this article we will learn how to send notification using topic-based message sending and how to open a specific page of an app when user taps the notification using Huawei AGC console.
Demo
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.
Things Need To Be Done
1) 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 AppGallery connect.
4) Enable push kit setting in Manage APIs section.
5) Provide the SHA Key in App Information Section.
6) Provide storage location.
7) In My Projects tab, navigate to Growing > Push and select service status Enable.
8) After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the Json file in the app folder of the android project.
9) Enter the below maven url inside the repositories of buildscript and allprojects (project build.gradle file):
Code:
maven { url 'http://developer.huawei.com/repo/' }
10) Enter the below plugin in the app build.gradle file:
Code:
apply plugin: 'com.huawei.agconnect'
11) Enter the below HMS Push kit dependencies in the dependencies section:
Code:
implementation 'com.huawei.hms:push:4.0.2.300'
12) Now sync gradle
Topic-based Message Sending
The topic messaging function provided by HUAWEI Push Kit, it allows you to send messages to multiple devices whose users have subscribed to a specific topic. We can write notification messages about the topic as required, and HUAWEI Push Kit sends the messages to correct devices in a reliable manner.
For example, users of a weather forecast app can subscribe to the weather topic and receive notification messages about the best weather for exterminating pests. Users who likes to travel can subscribe to travel information such as travel routes and travel guides.
Note the following items about topic messaging:
1) Topic messaging is best suited for delivering weather or other information that can be obtained publicly.
2) Topic messaging does not limit the number of subscriptions for each topic. However, HMS Push Kit has the following restrictions:
a) An app instance can subscribe to a maximum of 2,000 topics.
b) For Huawei devices running EMUI 10.0 or later, the version of HMS Core (APK) must be 3.0.0 or later. For Huawei devices running an EMUI version earlier than 10.0, the version of HMS Core (APK) must be 4.0.3 or later.
To send messages by topic, we need to complete the following process:
1) User needs to subscribe to a topic via app.
2) After subscribing to a topic, we can send messages to the user based on the topic he/she subscribed.
Subscribed/Unsubscribed to a topic
An app can subscribed/unsubscribed to any existing topics. When an app subscribes to a topic that does not exist, the system creates a topic with the name in HMS Push Kit server. Here we will use HmsMessaging class to subscribe/unsubscribe to a topic.
We will use the subscribe method in the HmsMessaging class to subscribe to a topic. We can add a listener to listen the task execution result to check whether the subscription task is successful. Below is the code to subscribe a topic:
Code:
public void subscribe(String topic) {
try {
HmsMessaging.getInstance(getActivity()).subscribe(topic)
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(Task task) {
if (task.isSuccessful()) {
Log.i("TAG", "subscribe Complete");
Toast.makeText(getActivity(),"subscribe Complete",Toast.LENGTH_LONG).show();
} else {
Log.e("TAG", "subscribe failed: ret=" + task.getException().getMessage());
Toast.makeText(getActivity(),"subscribe failed: ret=" + task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
Log.e("TAG", "subscribe failed: exception=" + e.getMessage());
Toast.makeText(getActivity(),"subscribe failed: ret=" + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
We will use the unsubscribe method in the HmsMessaging class to unsubscribe a topic.
Code:
public void unsubscribe(String topic) {
try {
HmsMessaging.getInstance(getActivity()).unsubscribe(topic)
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(Task task) {
if (task.isSuccessful()) {
Log.i("TAG", "unsubscribe Complete");
Toast.makeText(getActivity(),"unsubscribe Complete",Toast.LENGTH_LONG).show();
} else {
Log.e("TAG", "unsubscribe failed: ret=" + task.getException().getMessage());
Toast.makeText(getActivity(),"unsubscribe failed: ret=" + task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
Log.e("TAG", "unsubscribe failed: exception=" + e.getMessage());
Toast.makeText(getActivity(),"unsubscribe failed: exception=" + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
Sending notification based on the topic using console
The beauty of topic based subscription is we don’t need to add any push token to send notification. We only need to provide the topic in order to send notification and the notification will be served to the devices which subscribed to that particular topic.
Note: In order to make it work, we need to subscribe to a topic in the app as shown below:
Here we subscribed to sports as topic. Let us see how we can send notification using topic-based subscription.
Steps required in order to send notification based on topic using AGC console:
1) In My Projects tab, navigate Growing > Push Kit and select service status Enable.
2) After enabling the service, click Add Notification button.
3) Under content provide mandatory details like Name, Type, Display, Header, Title and Body. Select Open app in Action and Homepage in App page drop-downs, as shown below:
This is not all. For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202326236067510002&fid=0101187876626530001
More information like this, you can visit HUAWEI Developer Forum
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201332997357290022&fid=0101187876626530001
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Hello everyone. In this article, I would like to talk about Remote Configuration — A/B Testing. What are they and where are they used? I want to start with these.
Remote Configuration
With the service, you can make changes in the behavior and appearance of your application without any updates. This process is managed by determining various parameters on the Console.
Use Cases:
Displaying the Language by Country/Region
Displaying Different Content to Different Users
Adapting the App Theme by Time
Releasing New Functions
Configurations
Go to Growing> Remote Configuration. Click Enable now to enable Remote Configuration.
Add the Remote Configuration dependencies in the build.gradle file in the app directory.
Code:
implementation 'com.huawei.agconnect:agconnect-remoteconfig:1.4.0.300'
Development
I have prepared a demo app to explain this service better. I’ll talk about it step by step.
First, I set the parameter using the Parameter Management tab in the Remote Config tab.
Then I determined the condition in the Condition Management tab and defined it in the parameter tab.
After the integration process on AGC is completed, you can start writing code on the application. In the code part, you must first specify the parameter you defined in AGC. You can do this by using the “Map” object or “XML”. I used XML.
Code:
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/*
- Using a Map object
val mapDefault = mapOf("language" to "other",
"key2" to "val2",
"key3" to "val3",
"key4" to "val4")
- Using an XML resource file
<?xml version="1.0" encoding="utf-8"?>
<remoteconfig>
<value key="language">other</value>
</remoteconfig>
*/
val agConnectConfig = AGConnectConfig.getInstance()
agConnectConfig.applyDefault(R.xml.remote_config)
remoteButton = findViewById(R.id.remote)
remoteButton?.setOnClickListener {
agConnectConfig.fetch(0).addOnSuccessListener {
agConnectConfig.apply(it)
val languageResponse = agConnectConfig.getValueAsString("language")
Toast.makeText(this, languageResponse, Toast.LENGTH_LONG).show()
if (languageResponse == "en"){
showUpdateAlert("Language is English")
}
else if(languageResponse == "other"){
showUpdateAlert("Language is not English")
}
}.addOnFailureListener {
// fail fetching from remote config
it.printStackTrace()
}
}
}
After writing the code, you can test the Remote Configuration by making changes on the device according to the parameter.
A/B Testing
You can use the service to create one or more A/B tests engaging different user groups to compare your variants of app UI design, copywriting, product functions, or marketing activities for performance metrics and find the best one that meets user requirements.
Use Cases:
App UI Design Testing
App Copywriting Testing
App Function Testing
Configurations
Go to Growing > A/B Testing. Click Enable now in the upper right corner.
After the service is enabled, the page shown in the following figure is displayed.
Notifications Experiment:
When you want to send notifications to existing users, you can use the A/B Testing to find out which user is affected by what type of notification.
Remote Configuration Experiment:
You can use A/B Testing to determine specific behaviors for specific user groups in your application or if you want to learn how it affects users before updating your application.
Development
I used the Remote Configuration Experiment. I’ll try to explain the steps here.
Firstly, you need to access Analytics Kit to obtain the target experiment users and experiment data, and generate experiment reports.
Enable Analytics Kit
Add the following code to the build.gradle file in the app directory
Code:
implementation 'com.huawei.hms:hianalytics:4.0.2.300'
Create User Attributes in this way to use the User Attributes condition.
Create a condition on the Remote Configuration tab.
Use Conditions to create your parameter.
Then you will see a four-step screen when you press the Create Remote Configuration Experiment button on the A/B Testing tab.
Set the basic information of the test.
Specify the conditions for finding the target users in this step.
In this step, select your Remote Configuration parameter.
You can select the indicators you want to see as a result of the test. A maximum of 5 options can be selected.
After these steps, you can start writing your code based on the conditions in your application.
Code:
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/*
- Using a Map object
val mapDefault = mapOf("ABTest" to "c",
"key2" to "val2",
"key3" to "val3",
"key4" to "val4")
- Using an XML resource file
<?xml version="1.0" encoding="utf-8"?>
<remoteconfig>
<value key="ABTest">c</value>
</remoteconfig>
*/
val agConnectConfig = AGConnectConfig.getInstance()
agConnectConfig.applyDefault(R.xml.remote_config)
remoteButton = findViewById(R.id.remote)
remoteButton?.setOnClickListener {
agConnectConfig.fetch(0).addOnSuccessListener {
agConnectConfig.apply(it)
val abTestResponse = agConnectConfig.getValueAsString("ABTest")
if (abTestResponse == "a"){
showUpdateAlert("abTestResponse = A ")
}
else if(abTestResponse == "b"){
showUpdateAlert("abTestResponse = B ")
}
}.addOnFailureListener {
// fail fetching from remote config
it.printStackTrace()
}
}
}
Finally, you need to start your test on the A/B Testing screen. Sufficient data must be collected to obtain the test result.
I’d like to add the screenshots I took while I was doing the test.
Conclusion
By using these two services, you can diversify your application according to your users, thus increasing the interaction. Moreover, without updating the application.
I hope this article was useful.
References
Remote Configuration
A/B Testing
Nice article
Is huawei AB testing better than google firebase AB testing
riteshchanchal said:
Is huawei AB testing better than google firebase AB testing
Click to expand...
Click to collapse
For me, huawei's is better in some aspects. But I actually suggest you have a try by yourself.
The app menu of a quick app is forcibly displayed as stipulated in Quick App Specification 1070 and later versions. However, on some quick app pages, some content may be blocked by the app menu. For example, the sign-in entry is blocked by the app menu in the following figure. Although the menu is configured to be movable, users do not know that they can move it. As a result, user experience is affected.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
The following solutions are provided to solve this problem:
Separating the menu from any content displayed
Hiding the menu
Adding a message indicating that the menu is movable
Solution 1: Separating the Menu from Any Content Displayed
Configure a title bar for a quick app to leave a blank row for the app menu. The disadvantage of this solution is that a row of space is wasted.
Open the manifest.json file and change the value of titleBar to true.
"display": {
"fullScreen": false,
"titleBar": "true",
"menu": false,
"menuBarData": {
"draggable": true
},
"orientation": "portrait"
}
The following figure shows the modification result.
Solution 2: Hiding the Menu
Provide the package name to Huawei and Huawei will specially configure the quick app not to display the menu. The disadvantages of this solution are as follows: Functions accessed from the quick app default menu, such as adding an icon to the home screen and accessing Quick App Center are lost. These functions help improve the user retention rate and enable users to quickly access Quick App Center to experience more services. Therefore, this solution is not recommended unless otherwise specified.
Solution 3: Adding a Message Indicating that the Menu Is Movable
Display the menu and prompt users that the menu is movable by referring to the mask layer used in native apps.
This solution is implemented as follows:
In the template code as follows, code in red defines the layout of the mask, and custom sub-components are used to define tipContent and emitEvt. The advantage of using custom components is that they make code clear, concise, and readable.
<import name="menu_tip" src="./menutip.ux"></import>
<template>
<div>
<menu_tip id=“tip” if={{menuTipshow}} tip-content={{menutipContent}} onemit-evt=“emitHideTipMenuView”> //tip component
</menu_tip>
<web src="{{loadUrl}}" trustedurl="{{list}}" onpagestart="onPageStart"
onpagefinish="onPageFinish" onmessage="onMessage"
ontitlereceive="onTitleReceive" onerror="onError"
wideviewport="true" overviewmodeinload="true"
useragent="Mozilla/5.0 (Linux; Android 10; FRO-AN00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.93 Mobile Safari/537.36"
id="web"
multiwindow="true" supportzoom="true" allowthirdpartycookies="{{allowThirdPartyCookies}}">
</web>
</div>
</template>
Call the Data Storage API of the quick app and use onInit() to query the value of menutipflag from the database. If the value is false, the quick app is opened for the first time by a user. Then the mask is displayed to the user.
onInit: function () {
this.getMenuTipFlag();
},
getMenuTipFlag() {
var that = this;
storage.get({
key: 'menutipflag',
success: function (data) {
console.log(" storage.get success data=" + data);
that.menutipflag = data;
},
fail: function (data, code) {
console.log(" storage.get fail, code = " + code);
}
});
},
Save related variables to the database at a proper time based on the mask GUI design and the service logic of the quick app. In this example, the mask is designed to disappear when a user taps I got it, and the value of menutipflag is set to true and is saved to the database.
saveTipFlag() {
this.menutipflag = true;
storage.set({
key: 'menutipflag',
value: 'true',
success: function (data) {
console.log("saveTipFlag");
},
fail: function (data, code) {
console.log("saveTipFlag fail, code = " + code);
}
})
},
In conclusion, solution 3 is the optimal solution among the three options because it avoids the disadvantages of solution 1 and solution 2, and can be used to add a prompt message for a component or a function on a quick app GUI.
More information like this, you can visit HUAWEI Developer Forum
The app menu of a quick app is forcibly displayed as stipulated in Quick App Specification 1070 and later versions. However, on some quick app pages, some content may be blocked by the app menu. For example, the sign-in entry is blocked by the app menu in the following figure. Although the menu is configured to be movable, users do not know that they can move it. As a result, user experience is affected.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
The following solutions are provided to solve this problem:
Separating the menu from any content displayed
Hiding the menu
Adding a message indicating that the menu is movable
Solution 1: Separating the Menu from Any Content Displayed
Configure a title bar for a quick app to leave a blank row for the app menu. The disadvantage of this solution is that a row of space is wasted.
Open the manifest.json file and change the value of titleBar to true.
Code:
"display": {
"fullScreen": false,
"titleBar": "true",
"menu": false,
"menuBarData": {
"draggable": true
},
"orientation": "portrait"
}
The following figure shows the modification result.
Solution 2: Hiding the Menu
Provide the package name to Huawei and Huawei will specially configure the quick app not to display the menu. The disadvantages of this solution are as follows: Functions accessed from the quick app default menu, such as adding an icon to the home screen and accessing Quick App Center are lost. These functions help improve the user retention rate and enable users to quickly access Quick App Center to experience more services. Therefore, this solution is not recommended unless otherwise specified.
Solution 3: Adding a Message Indicating that the Menu Is Movable
Display the menu and prompt users that the menu is movable by referring to the mask layer used in native apps.
This solution is implemented as follows:
In the template code as follows, code in red defines the layout of the mask, and custom sub-components are used to define tipContent and emitEvt. The advantage of using custom components is that they make code clear, concise, and readable.
Code:
<import name="menu_tip" src="./menutip.ux"></import>
<template>
<div>
<menu_tip id=“tip” if={{menuTipshow}} tip-content={{menutipContent}} onemit-evt=“emitHideTipMenuView”> //tip component
</menu_tip>
<web src="{{loadUrl}}" trustedurl="{{list}}" onpagestart="onPageStart"
onpagefinish="onPageFinish" onmessage="onMessage"
ontitlereceive="onTitleReceive" onerror="onError"
wideviewport="true" overviewmodeinload="true"
useragent="Mozilla/5.0 (Linux; Android 10; FRO-AN00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.93 Mobile Safari/537.36"
id="web"
multiwindow="true" supportzoom="true" allowthirdpartycookies="{{allowThirdPartyCookies}}">
</web>
</div>
</template>
Call the Data Storage API of the quick app and use onInit() to query the value of menutipflag from the database. If the value is false, the quick app is opened for the first time by a user. Then the mask is displayed to the user.
Code:
onInit: function () {
this.getMenuTipFlag();
},
getMenuTipFlag() {
var that = this;
storage.get({
key: 'menutipflag',
success: function (data) {
console.log(" storage.get success data=" + data);
that.menutipflag = data;
},
fail: function (data, code) {
console.log(" storage.get fail, code = " + code);
}
});
},
Save related variables to the database at a proper time based on the mask GUI design and the service logic of the quick app. In this example, the mask is designed to disappear when a user taps I got it, and the value of menutipflag is set to true and is saved to the database.
Code:
saveTipFlag() {
this.menutipflag = true;
storage.set({
key: 'menutipflag',
value: 'true',
success: function (data) {
console.log("saveTipFlag");
},
fail: function (data, code) {
console.log("saveTipFlag fail, code = " + code);
}
})
},
In conclusion, solution 3 is the optimal solution among the three options because it avoids the disadvantages of solution 1 and solution 2, and can be used to add a prompt message for a component or a function on a quick app GUI.
1. Environment
SDK Version:agconnect-storage:1.3.0.300
Platform:Cocos Creator
Device:HUAWEI P40 Pro
AppGallery Connect:
https://developer.huawei.com/consumer/en/service/josp/agc/index.html
2. Enabling and Configuring Cloud Functions in AppGallery Connect
Note: Currently, Cloud Functions is still under beta state. To use the service, you need to send an email for application. For details, check:
https://developer.huawei.com/consum...allery-connect-Guides/agc-cloudfunction-apply
1. Create an app first and add it to a project, or select an app from the project list on the My projects page in AppGallery Connect.
Under the project, go to Build > Cloud Functions, and click Enable now.
2. Create a function based on the description in the following codelab.
https://developer.huawei.com/consumer/en/codelab/CloudFunctions/index.html#4
3. Create an HTTP trigger and save the suffix of the value of Trigger URL in the Details area as the trigger identifier of future client requests.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
3. Integrating the Cloud Functions SDK in Cocos Creator
1. Integrate the SDK.
Official documentation:
https://docs.cocos.com/creator/manual/en/cocos-service/agc-applinking.html
1. On the Service panel of Cocos Creator, find Cloud Functions. Currently, the Cloud Functions SDK supports only the Android platform.
2. Before integrating a service, you need to associate the service with an app. Click Association. In the dialog box that is displayed, click Create. The Cocos console is displayed.
3. On the Cocos console, create a game.
4. Go back to Cocos Creator and create, refresh, or select an association.
5. Return to the Cloud Functions page, and enable the service.
2. Download the JSON file.
1. Go to Project settings in AppGallery Connect and download the latest agconnect-services.json file.
2. Save the downloaded agconnect-services.json file to the settings directory in your Cocos project.
4. Configuring the UI Layout
Configure buttons for triggering a cloud function, obtaining the timeout interval, and setting the timeout interval separately.
5. Cloud Functions Development
1. Initialize Cloud Functions in the start block.
Code:
start () {
this._func = huawei.agc.func.funcService;
},
2. Call Cloud Functions with input parameters.
Code:
callWithParam:function() {
this._func.wrap("testcodelab-$latest").call((err, data) => {
if (err !== null) {
console.log("Cloud Function", `error: ${JSON.stringify(err)}`);
}
console.log("Cloud Function", `result: ${JSON.stringify(data)}`);
}, {
year: "2020",
}
);
},
3. Call Cloud Functions without input parameters.
JavaScript:
callWithoutParam:function() {
this._func.wrap("testcodelab-$latest").call((err, data) => {
if (err !== null) {
console.log("Cloud Function", `error: ${JSON.stringify(err)}`);
}
console.log("Cloud Function", `result: ${JSON.stringify(data)}`);
});
},
4. Obtain and set the timeout interval of a function.
JavaScript:
setTime:function() {
this._func.wrap("testcodelab-$latest").setTimeout(100,3);
console.log("Cloud Function", `setTime: ` + 100);
},
getTime:function() {
let currTime = this._func.wrap("testcodelab-$latest").getTimeout();
console.log("Cloud Function", `currTime: ` + currTime);
},
6. Packaging and Testing
In Cocos Creator, go to Project > Build…, package an Android app, and install it to your device. To verify the functions, click the buttons from top to bottom.
If the following information is displayed in JavaScript logs, the integration is successful.
7. Summary
Cloud Functions allows you to keep all functions and related code on the cloud side. You only need to call the wrap.call method to trigger the functions, which reduces the code amount and package size of your APK package.
For more details, please check:
Cloud Functions development guide:
https://developer.huawei.com/consum...connect-Guides/agc-cloudfunction-introduction
Cocos documentation:
https://docs.cocos.com/creator/manual/en/cocos-service/agc-cloudfunc.html