Introduction
Flight booking app allows user to search and book flight. In this article, we will integrate Huawei Cloud DB into demo flight booking application.
Huawei Cloud DB is a computing platform that provides functionality of traditional database with cloud computing. The cloud DB ensures data availability, reliability, consistency, security and enables seamless data synchronization between the device and cloud, and supports offline application operations, helps developers quickly develop device-cloud and multi-device synergy applications. Cloud DB builds the Mobile backend as a service capability for the AppGallery Connect platform. This provides developer to focus on application services, delivering the efficient product.
For prerequisite and set up, refer to part 1.
Usecase
1. Once user books the flight from the app, we will store flight booking information in cloud DB.
2. User can navigate to Itinerary Screen from navigation drawer to see all the flight booked by him in past.
{
"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"
}
Permissions
By default, users who access Cloud DB from the AppGallery Connect console or cloud function have all permissions, as they are assigned with administrator role.
Everyone : All users. This role has only query permission granted.
Authenticated user: Users who have passed the AppGallery Connect login.This role has the query permission by default and upsert and delete permission can be granted.
Data creator: Authenticated users who create data. Data creators can upsert or delete the data created only by themselves. The information about data creator is stored in data table system records. This role has all permissions by default and can customize the permissions.
Administrator: Developers who access Cloud DB from the AppGallery Connect console . This role has all permissions by default and can customize the permissions.
Accessing Cloud DB
Since Cloud DB is in beta stage, developers need to send a mail to activate this service in their app. Developer needs to create Huawei developer account. Once account created, developers need to create an app in App Gallery connect. After completing all the necessary steps, developer have to request the activation of the service by sending an e-mail to [email protected] with the subject as "[Cloud DB]-[Company name]-[Developer account ID]-[App ID]". To access the app ID, see Querying App Information. Usually it takes 1 to 3 days for activation, once activated , developer can integrate cloud DB service in their app.
Getting started with Cloud DB
1. Log in to AppGallery Connect and select My Projects.
2. Select Application for which you want to create object types.
3. Choose Build > Cloud DB from left panel.
4. Click on Enable now.
5. Click Add to create object type.
6. Set Object Type Name to EaseMyFlight, and click Next.
7. Click on Add fields , add the fields and click Next.
8. Click Add Index, set Index Name and Indexed Field, and click Next.
9. Add permissions as follows and click Next. (For Everyone , upsert and delete access is not allowed).
10. Click Ok. Object types are created and displayed in the object type list.
11. Click Export. Select JAVA as export file name. Enter the package name of JAVA file. package name can contain Letters A–Z or a–z, Digits 0–9, Special characters _ and .
12.Click Export. The file that contains all object types will be downloaded. Add the exported JAVA file in your project.
Cloud DB Zone
1. Log in to AppGallery Connect and select My apps.
2. Select Application for which you want to create object types.
3. Choose Build > Cloud DB from left panel.
4. Click Cloud DB Zones tab.
5. Click Add to navigate to the Cloud DB zone creation page.
6. Enter easeMyFlightZone in the Cloud DB Zone Name text box.
Development
Prerequisites
Auth Service has to be integrated. Follow this tutorial to integrate Auth Service.
1. Add cloud DB SDK dependecy in app- level build.gradle.
Code:
// Add the Cloud DB SDK.
implementation 'com.huawei.agconnect:agconnect-database:1.2.1.301'
2. Add compatibility mode to JDK 1.8 in app- level build.gradle.
Code:
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
3. Initialize AGConnectCloudDB in Application class.
Code:
public class EaseMyFlightApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
initAGConnectCloudDB(getApplicationContext());
}
public static void initAGConnectCloudDB(Context context) {
AGConnectCloudDB.initialize(context);
}
}
4. Get the instance of AGConnectCloudDB and create object types.
Code:
mCloudDB = AGConnectCloudDB.getInstance(); mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
5. Create the Cloud DB zone configuration file and open the Cloud DB zone.
Code:
mConfig = new CloudDBZoneConfig("easeMyFlightZone", CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
mConfig.setPersistenceEnabled(true);
try {
mCloudDBZone = mCloudDB.openCloudDBZone(mConfig, true);
} catch (AGConnectCloudDBException e) {
Log.w(TAG, "openCloudDBZone: " + e.getMessage());
}
6. Writing Data
Data can be entered either manually from App Gallery Connect(administrator or data creater) or programmatically(authorized user) by using cloud DB SDK , if user has the permission. If same value in primary key is used, data will be modified.
Code:
public void insertDataToCloudDB(EaseMyFlight info) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
CloudDBZoneTask<Integer> upsertTask = mCloudDBZone.executeUpsert(info);
upsertTask.addOnSuccessListener(new com.huawei.agconnect.cloud.database.OnSuccessListener<Integer>() {
@Override
public void onSuccess(Integer integer) {
Log.w(TAG, "upsert " + integer + " records");
}
}).addOnFailureListener(new com.huawei.agconnect.cloud.database.OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, "Insertion failed : "+ e.getMessage());
e.printStackTrace();
}
});
}
More information, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201388320242800533&fid=0101187876626530001
Does it supports BLOB Data Type ?
Related
More information like this, you can visit HUAWEI Developer Forum
Introduction
Huawei Game service provides a centralized place for you to manage game services and configure metadata for authorizing and authenticating your game. Using Huawei game service, developer can access range of capabilities to help develop your games more efficiently.
Features
1. Developers can promote their game efficiently and quickly.
2. Developers can easily build the foundation of game by implementing features like achievements and events.
3. Developers can perform in-depth operations tailored to their game and their users.
In this article, we will implement event feature provided by Huawei game service in Tic tac toe game.
{
"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"
}
Prerequisites
1. Developer has created an application on App Gallery Connect. Follow Creating an App.
2. Integrating app gallery connect SDK. Please refer to AppGallery Connect Service Getting Started.
3. Developer has integrated Huawei Account kit. Follow this tutorial to integrate account kit.
4. HUAWEI mobile phone with HMS Core 4.0.0.300 or later installed.
Setup:
1. Enable Huawei Game service in Manage APIS. Please refer to Service Enabling.
2. Add appgallery connect plug-in in app-level build.gradle
Code:
apply plugin: 'com.huawei.agconnect'
3. Add following dependencies in app-level build.gradle and click on Sync Now and wait till synchronization is done.
Code:
dependencies {
implementation 'com.huawei.hms:base:4.0.4.301'
implementation 'com.huawei.hms:hwid:4.0.4.300'
implementation 'com.huawei.hms:iap:4.0.4.300'
implementation 'com.huawei.hms:game:4.0.3.301'
}
Initialization
Once Initial set up is done, let’s implement Huawei game service in Tic tac toe game
1. Add the following code in onCreate() method of Application class.
Code:
public class GameServiceApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
HuaweiMobileServicesUtil.setApplication(this);
}
@Override
public void onTerminate() {
super.onTerminate();
}
}
2. To initialize the game
Code:
private void init() {
JosAppsClient appsClient = JosApps.getJosAppsClient(this, null);
appsClient.init();
Log.i(TAG, "initialization success");
}
Signin In
1. When app is launched, Huawei sign-in page is displayed.
2. User enters Huawei Huawei ID and password to sign in.
3. After a successful sign in, the app obtains player information corresponding to Huawei ID.
Please refer to this article for sign in implementation.
Game Events
The Game events allow developer to collect specific data generated by players and store them on Huawei game server for AppGallery connect. In this article, we will collect data pertaining to player win. Every time players win the match, we will store it in Huawei game server.
Creating an Event in AppGallery Connect
1. Sign in to AppGallery Connect and select My apps.
2. Select an app from the app list to create an event.
3. Click the Operate tab and go to Products > Game Event. Click Create.
4. Configure the event information and click Save.
5. Check your event ID on the event list and properly save the ID for event development.
Implementation of Event
1. To initialize EventsClient instance
Code:
EventsClient client = Games.getEventsClient(this, mAuthHuaweiId);
mAuthHuaweiId is obtained during sign in.
2. To submit the event
Code:
client.grow(eventId, growAmount);
eventId indicates the ID of the event which is generated while defining the event in AppGallery connect. In our app we will submit the event everytime players win the match.
The growAmount parameter specifies an increment amount of the event value.
To Obtain Events
Following code can be used to obtain the events.
Code:
Task<List<Event>> task = client.getEventList(forceReload);
forceReload is a Boolean type used to indicate whether to obtain data stored on the Huawei game server or locally cached data.
Following code shows how list of events are returned.
Code:
task.addOnSuccessListener(new OnSuccessListener<List<Event>>() {
@Override
public void onSuccess(List<Event> data) {
if (data == null) {
Log.w("Event", "event is null");
return;
}
for (Event event : data) {
Log.i("Event", "event id:" + event.getEventId());
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
if (e instanceof ApiException) {
String result = "errorCode:"
+ ((ApiException) e).getStatusCode();
Log.e("Event", result);
}
}
});
We will show the retrieved events list in recyclerview. Clicking on event list item will show details about the events.
Code:
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Event event = eventList.get(position);
final String eventId = event.getEventId();
Glide.with(context).load(event.getThumbnailUri()).into(holder.eventImage);
holder.eventName.setText(event.getName());
holder.eventAmonut.setText("value:"+event.getValue() + "#" + event.getLocaleValue());
holder.eventDes.setText(event.getDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBtnClickListener.onItemClick(position);
}
});
holder.eventReport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBtnClickListener.reportEvent(eventId);
}
});
}
Screenshots
Summary
In this article, we understood initial setup and game event features of Huawei Game Service. In next article, we will discuss more features provided by Huawei Game service.
Source code can be downloaded from https://github.com/DTSE-India-Community/Huawei-Game-Service
How many days it will take to get data reflected in AGC.
More information like this, you can visit HUAWEI Developer Forum
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202333898987840045&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"
}
Huawei Awareness Kit provides our application to obtain information such as current time, location, behavior, audio device status, ambient light, weather, and nearby beacons. Using this information we can get an advantage over user's current situation more efficiently and can manipulate data for better user experience.
In this article, we will use weather information using HMS Awareness Kit for manipulating warm up exercise for user.
Demo
In the above demo, the warm up exercise for user will get change according to the weather condition. Here the weather condition is divided into two parts:
1) Outdoor warm up exercise: When the weather condition is normal such as sunny or not raining, then the warm up exercise will get change to running.
2) Inside warm up exercise: When the weather condition is abnormal such as raining or snow fall, then the warm up exercise will get change to invisible jumping rope, burpee and squats.
By this way we are providing user a better experience without avoiding any exercise due to certain condition. It’s a win-win situation for developers to not to lose any user due to bad user experience.
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 awareness kit setting in Manage APIs section.
5) Provide the SHA Key in App Information Section.
6) Provide storage location.
7) 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.
8) Enter the below maven url inside the repositories of buildscript and allprojects (project build.gradle file):
Code:
maven { url ‘http://developer.huawei.com/repo/’ }
9) Enter the below plugin in the app build.gradle file:
Code:
apply plugin: ‘com.huawei.agconnect’
10) Enter the below HMS Push kit dependencies in the dependencies section:
Code:
implementation ‘com.huawei.hms:awareness:1.0.6.301’
11) Enter the below permission in android manifest file
Code:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
12) Now Sync the gradle.
Weather Awareness
It is used for providing weather information such as current day or next seven days weather information of a specific device location. It does not support barrier information or function.
Code:
public void sendWeatherId(){
Awareness.getCaptureClient(this).getWeatherByDevice()
.addOnSuccessListener(new OnSuccessListener<WeatherStatusResponse>() {
@Override
public void onSuccess(WeatherStatusResponse weatherStatusResponse) {
WeatherStatus weatherStatus = weatherStatusResponse.getWeatherStatus();
List<HourlyWeather> hourlyWeather = weatherStatus.getHourlyWeather();
Utility.setWeatherId(getApplicationContext(),hourlyWeather.get(1).getWeatherId());
if(Utility.getWeatherId(getApplicationContext())!=0){
goToValidPage();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e("TAG", "get Hourly weather failed");
}
});
}
The above code is used to get the weather information such as sunny, rain, cloudy etc. Using this information we will manipulate the warm up exercise and show user the list of exercise.
getWeatherByDevice
This method is used to obtain the weather information using the current location of a device. There are some restriction using this method:
1) The total number of capture API calls every 5 seconds cannot exceed 20
2) The total number of capture API calls every hour cannot exceed 1000
3) This function is available only on device with API level 24 or later
4) ACCESS_FINE_LOCATION permission is needed in android manifest file.
WeatherStatus
This is the main API where we will fetch the weather id. Using this id we will manipulate the exercise. This API contain five methods:
1) getAqi()
2) getWeatherSituation()
3) getDailyWeather()
4) getHourlyWeather()
5) getLiveInfo()
Here we will use getHourlyWeather to obtain weather information in the next 24 hours. The information will fetch weather ID, time, temperature and rainfall probability.
Opening YouTube Video in HMS devices
Code:
public static void watchYoutubeVideo(Context context, String id){
try {
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + id));
context.startActivity(webIntent);
} catch (ActivityNotFoundException ex) {
}
}
The Id here is YouTube Id.
CountDownTime
As the name implies to counts down the time specified in milliseconds.
Code:
mCountDownTimer = new CountDownTimer(TIMER_DURATION, TIMER_INTERVAL) {
@Override
public void onTick(long millisUntilFinished) {
txtTimer.setText("00:"+(millisUntilFinished / 1000 < 10 ? "0"+ millisUntilFinished / 1000 : String.valueOf(millisUntilFinished / 1000)));
mTimeRemaining = millisUntilFinished; // Saving timeRemaining in Activity for pause/resume of CountDownTimer.
}
@Override
public void onFinish() {
mCountDownTimer.cancel();
Intent intent = new Intent(ReadyActivity.this, CurrentWorkoutActivity.class);
startActivity(intent);
finish();
}
}.start();
Timer
In case user go for run we need to have a timer to capture the duration of its completion.
Code:
private void timer (){
Timer timer = new Timer();
countTimer = 0;
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
String s_time = String.format("%02d:%02d:%02d",
countTimer / 3600,
(countTimer % 3600) / 60,
countTimer % 60);
System.out.println("TIMER >>>" + s_time);
txtTimer.setText(s_time);
if (!pauseTimer) countTimer++;
}
});
}
}, 1000, 1000);
}
What we learn?
We learn how to manipulate data using HMS Weather Awareness Kit and also situation where we need the most.
GitHub
Very soon I am going to post the entire code on GitHub. So come back again to check it out.
For more reference
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/service-introduction-0000001050031140-V5
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/weather-awareness-0000001050121038-V5
In the previous post, we learned the advantages of Account Kit: one-click sign-in authorization in any scenario, secure and reliable services, and convenient integration, as well as giving apps access to the global HUAWEI ID base of potential users. A QR code is also provided at the end of the post for you to download the demo app to experience HUAWEI ID sign-in authorization. The demo has integrated three Account Kit APIs (four in total), and is easy to develop. In this article, we'll show you the demo development to get you familiar with Account Kit.
Before you start, use a browser to scan the QR code below to try the demo app.
{
"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"
}
(Note: The app may collect relevant information for user statistics.)
Preparing for Demo Developmentl Install Android Studio 3.5 or later.
l Install JDK 1.8 or later.
l Use SDK Platform 19 or later.
l Use Gradle 4.6 or later.
l If you haven't already, register as a developer on HUAWEI Developers.
l Download the sample code of the demo from GitHub.
Configuring the Running Environment (2 minutes)1. Use Android Studio to open the demo project.
2. Go to File > Settings > Plugins > Marketplace, enter HMS Toolkit in the search box, and click Install. Note: HMS Toolkit must be version 5.2.0.300 or later.
For details, please refer to Installing HMS Toolkit.
3. Create a package and rename it to something like com.hxb.account in the project. Then, copy the code in the com.huawei.hms.accountsample package to your package, and change the value of package and applicationId to your package name. (Do not use the existing package name in the demo project because it is already registered on HUAWEI AppGallery.)
First, create a package. Move the MainActivity class to your package so that you can search for related files easily during the build.
Change package in the AndroidManifest.xml file to com.hxb.account.
Change applicationId in the build.gradle file to com.hxb.account.
4. Go to HMS > Configuration Wizard to check the environment configuration. If you have not signed in with a HUAWEI ID, Toolkit will first prompt you to do so.
On the Configuration Wizard page displayed, you are prompted that no app corresponding to the package name was detected under the signed-in HUAWEI ID.
Click Link to go to AppGallery Connect and create an app manually:
(a) Click Release.
(b) Click Add project.
(c) Create a project.
(d) Click Add app.
(e) Add the project.
After creating, go back to the Configuration Wizard page and click Retry. This time, the check will be successful.
5. Choose Account Kit.
On the Configuration Wizard page, click Add Kits and choose Account Kit.
The following page will be displayed.
6. Choose a certificate. You can choose Use Android debug certificate and click Generate to generate a certificate fingerprint, as shown in the following figure.
7. Click Next to automatically complete other configurations including toggling on the Account Kit switch in AppGallery Connect, configuring the signing certificate fingerprint, downloading the agconnect-services.json file to the project directory, configuring obfuscation scripts, and adding build dependencies and APK fingerprint required for integrating the Account SDK to the build.gradle file. Once these configurations are completed, the following page will be displayed. If you run into errors, please refer to the corresponding guide on the page.
Packaging and Testing the Demo on Remote Real Device Provided by ToolkitAfter configuration, go to HMS > Cloud Debugging to package and test the demo app.
Select the desired device model.
Click Run to test the demo app.
Key Code for Demo Development1. UI Design
Account Kit provides four main APIs for signing in, silently signing in, revoking authorization, and signing out. The demo app integrates the first three.
In the above figure, the Sign in with HUAWEI ID button is created with an encapsulated standard control. Please follow HUAWEI ID Sign-In Button Usage Rules when using the icon elements provided by Huawei.
Code:
<p style="line-height: 1.5em;"><com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android
:layout_width
="wrap_content"
android
:layout_height
="wrap_content"
/>
1. Key Code for APIs
(1) Sign-in
Use case: Account Kit, compliant with OAuth 2.0 and OpenID Connect, supports sign-in in two modes: authorization code (for apps with their own servers only) and ID token modes. Select the mode you need.
Code:
private void signIn() {
mAuthParam = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setIdToken()
.setAccessToken()
.createParams();
mAuthManager = AccountAuthManager.getService(AccountActivity.this, mAuthParam);
startActivityForResult(mAuthManager.getSignInIntent(), Constant.REQUEST_SIGN_IN_LOGIN);
}
As shown, setIdToken() means use the ID token mode for authorization. The other mode will show setAuthorizationCode() instead. Their difference will be described later. getSignInIntent() is the API for ID sign-in authorization.
Process the result after authorization.
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN) {
// Successful sign-in.
// Obtain user information through parseAuthResultFromIntent.
Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
if (authAccountTask.isSuccessful()) {
AuthAccount authAccount = authAccountTask.getResult();
Log.i(TAG, authAccount.getDisplayName() + " signIn success ");
Log.i(TAG, "AccessToken:\n" + authAccount.getAccessToken());
Log.i(TAG, "OpenId:\n" + authAccount.getOpenId());
Log.i(TAG, "Email:\n" + authAccount.getEmail());
Log.i(TAG, "UnionId:\n" + authAccount.getUnionId());
// Download avatar by using AsyncTask.
NetService = new NetService(new URLPostHandler() {
@Override
public void PostHandler(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
textView.setText(authAccount.getDisplayName());
}
});
netService.execute(authAccount.getAvatarUriString());
} else {
Log.i(TAG, "signIn failed: " + ((ApiException)
authAccountTask.getException()).getStatusCode());
}
}
}
(2) Silent sign-in
Use case: Authorization is required only on first sign-in to your app using a HUAWEI ID. Subsequent sign-ins using the same HUAWEI ID do not require any authorization.
Code:
private void silentSignIn() {
Task<AuthAccount> task = mAuthManager.silentSignIn();
task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
@Override
public void onSuccess(AuthAccount authAccount) {
Log.i(TAG, "silentSignIn success");
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// If failed, use getSignInIntent.
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
signIn();
}
}
});
}
Call silentSignIn() to implement silent sign-in.
(3) Authorization revoking
Use case: To improve privacy security, users can unauthorize your app.
Code:
private void cancelAuthorization() {
Task<Void> task = mAuthManager.cancelAuthorization();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
imageView.setImageDrawable(null);
textView.setText("");
Log.i(TAG, "cancelAuthorization success");
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, "cancelAuthorization failure:" + e.getClass().getSimpleName());
}
});
}
Call cancelAuthorization() to revoke authorization.
For more information about Account Kit, please visit:
l Development guide
l Codelab
l Video course (and the course for HMS Core 4.0.)
For more details, you can go to:
Our official website
Demo of Analytics Kit
Android SDK integration documentation
iOS SDK integration documentation
Web SDK integration documentation
Quick app SDK integration documentation
Checkout in forum
With Cloud Functions, you can configure a CLOUDDB trigger to call a function when data is entered, deleted, or modified in Cloud DB.
The Cloud DB service has been released with a JavaScript Server SDK, which can be used in the Node.js environment that the Cloud Functions service supports. In this article, I will elaborate on how to enter and query data with the Cloud DB JavaScript Server SDK in Cloud Functions.
{
"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"
}
Enabling Required ServicesYou need to enable two services.
First of all, sign in to AppGallery Connect and perform the following operations:
Enable Cloud Functions. Click My projects, click your project card, and go to Build > Cloud Functions. On the Cloud Functions page, click Enable now. Click + New Function to create a function.
Enable Cloud DB. Click My projects, click your project card, and go to Build > Cloud DB. On the Cloud DB page, click Enable now and then create an object type and a Cloud DB zone.
Configuring the JavaScript Server SDK of Cloud DBHere, I will use the src file in the Huawei service demo to demonstrate how the JavaScript Server SDK is configured. You can also download the file and use it for your own file from GitHub.
Then you need to do the following in AppGallery Connect:
Export an object type.On the Cloud DB page, export the BookInfo object type to a JS file, and then add it to the model directory of your project.
Download the authentication credential.Go to Project settings > Server SDK. On the Server SDK tab page, click Create for API client first, and then click Download credential to download the authentication credential. Finally, add it to the model directory of your project
Modify the path to the credential.You need to modify the path to the credential as it was saved to the model directory. In the CloudDBZoneWrapper.js file (use the _dirname method to obtain the file), modify the initialization code as follows:
Code:
let api_client_name = "agc-apiclient-testDB.json";
let path = require('path');
let api_client_path = path.join(_dirname,api_client_name);
agconnect.AGCClient.initialize(agconnect.CredentialParser.toCredential(api_client_path));
Configure a handler.You can either use the Start.js file as the handler by default or create a new one. For example, the inde.js file is created as a handler. The sample code is as follows:
Code:
const CloudDBZoneWrapper = require("./model/CloudDBZoneWrapper.js");
let myHandler = async function(event, context, callback, logger) {
logger.info(JSON.stringify(event));
logger.info("event start");
const cloudDBZoneWrapper = new CloudDBZoneWrapper();
const bookInfo = cloudDBZoneWrapper.getSingleBook();
// Update and insert a list of books.
await cloudDBZoneWrapper.upsertBookInfos(bookInfo);
let result = {"message":"Run Success"}
callback(result);
}
module.exports.myHandler = myHandler;
Packaging Your Project and Configuring a TriggerYou need to package your project, upload it to Cloud Functions, and test it with events. The handler file should be saved in the root directory.
Sign in to AppGallery Connect and go to the Cloud Functions page. Upload your package and set the name of the handler to index.myHandler
Configure a CLOUDDB trigger. Click + Add Trigger and configure the type, Cloud DB zone, and object type for the trigger.
Testing the FunctionIn AppGallery Connect, go to Cloud Functions > Test.
Configure a trigger event according to the documentation
If you need to configure a data insertion event, add the following sample code.
Code:
{
"records": [{
"before": null,
"after": {
"id": "11111",
"bookName": "user1"
}
}],
"objectTypeName": "BookInfo",
"naturalStoreName": "QuickStartDemo"
}
Check the test result.
ReferenceCloud Functions
Defining a programming model
Cloud DB JavaScript Server SDK
Huawei AppGallery Connect’s App Messaging service allows you to send targeted, useful in-app messages to your users.
The look and content of messages are completely customisable, and there is a wide range of triggers and filters that can be used to decide who will receive a message and when.
Let's take a look today at how we can set this up to work within a flutter project.
As always we will start with a fresh project but of course, you can just as easily use this guide to build the service into an app you already have!
Installing the Flutter Environment
Download the Flutter SDK.
Decompress the package to any directory.
Add the Flutter command file to the environment variable.
Download the Flutter and Dart plugins in Android Studio.
{
"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"
}
Enabling the Service and Creating a Flutter projectSign in to AppGallery Connect, click My projects, click your project, go to Grow > App Messaging, and click Use now. For more information, please refer to App Messaging.
If you do not have an Android project, create one first.
After completing these steps, you can start creating an in-app message.
Click New in the upper right corner.
Set Name and Description
Set the style and content and click Next.
Select a message type from the Layout drop-down list, and set its style and content. Currently, the Modal, Image, and Banner message types are supported.
Set target users and click Next.
In App, select the name of the app package for which you need to publish the in-app message.
You can click New condition to add a condition for matching target users, which include app version, OS version, language, country/region, audience, and more. Among the types, User attributes are defined under HUAWEI Analytics > Management > User attributes, and Prediction is defined by creating prediction tasks under My projects > Grow > Prediction.
Set the message sending time
Message display is triggered by specific events. App Messaging supports two types of trigger events: preset events and HUAWEI Analytics events.
(Optional) Set conversion events. Before setting a conversion event, you need to toggle it on first, which can be done as follows:
Go to HUAWEI Analytics > Management > Events and toggle Mark as conversion event and Event switch on for the specified event. In addition to the events the SDK collects, you can also create a preset or custom event for event tracking and analysis.
Finally, Click Save or Publish.
Integrating the Service SDKAdd dependenciesStart by creating a Flutter project in Android Studio (or opening one).
Then add the agconnect-services.json file from your AppGallery project to the android/app directory
Within the project level build.gradle file make sure to include the huawei maven repo and add the agcp package as a dependency.
Code:
buildscript {
repositories {
google()
mavenCentral()
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.4'
classpath 'com.huawei.agconnect:agcp:1.6.2.300'
}
}
Next in your app level build.gradle apply the agconnect plugin as so:
Code:
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.huawei.agconnect'
Then in your pubspec.yaml file add the App Messaging SDK dependency.
Code:
dependencies:
flutter:
sdk: flutter
agconnect_appmessaging: ^1.2.0+300
Displaying an In-App MessageIf you choose to display a message using the default message layout, the development process is totally coding-free.
By integrating the SDK as above you are all good to go, your creating message will be displayed as per its filters and triggers.
You can also call APIs provided by the service SDK to customize your in-app message.
Customising the Message LayoutAdd the following code to onCreate in MainActivity,
Code:
AGCAppMessagingCustomEventStreamHandler.addCustomView();
so that the service SDK can listen to the corresponding event and apply the customized layout.
Code:
streamSubscriptionDisplay = agconnectAppmessaging.customEvent.listen((event) {
showDialog(context ,event.toString());
agconnectAppmessaging.handleCustomViewMessageEvent
(AppMessagingEventType.onMessageDismiss(AppMessagingDismissTypeConstants.CLICK));
});
Then the message is displayed in your app.
Code:
void _showDialog(BuildContext context, String content) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
key: Key("dialog"),
title: Text("Result"),
content: Text(content),
actions: <Widget>[
FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
}
Testing an In-App MessageApp Messaging allows you to test an in-app message before it is published. You need to obtain the Anonymous Application Identifier (AAID) of your test device by adding the following code to your Android app module.
Code:
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
textView.setText(aaid);
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
Sign in to AppGallery Connect, go to Grow > App Messaging > Messages, find the message that you created, click and select Test in the Operation column.
Click Add test user and enter the AAID
Click Save. Check whether the test message is properly displayed on your test device