Huawei Flight Booking Application (Cloud Storage) – Part 9 - Huawei Developers

Introduction
Flight booking app allows user to search and book flight. In this article, we will integrate Huawei Cloud Storage into demo flight booking application.
Huawei storage is versatile and maintenance-free.This enables us to safely and economically store large quantities of data such as photos, audios and videos generated by users.
The service is stable, secure, efficient, and easy-to-use, and can free you from development, deployment, O&M, and capacity expansion of storage servers. Developers do not need to pay attention to indicators such as availability, reliability, and durability and can focus on service capability building and operations, improving user experience.
For prerequisite and set up, refer to part 1.
Usecase
1. Once user books the flight from the app, we will store flight ticket in Huawei cloud storage.
2. User can navigate to ItineraryActivity from navigation drawer to browse all the flight ticket booked by him in past.
Accessing Huawei Cloud Storage
Since Cloud Storage is still in Beta state, we need to send an application email to [email protected] to apply for the service.Set your email title in the following format: [Cloud Storage]-[Company name]-[Developer account ID]-[Project ID]. For details about how to query the developer account ID and project ID, refer to Querying the Developer Account ID and Project ID.
Usually it takes 1 to 3 days for activation, once activated, developer can integrate cloud DB service in their app.
Getting started with Cloud Storage
1. Log in to AppGallery Connect and select My Projects.
2. Select Application for which you want integrate Cloud storage.
3. Enable Cloud storage settings in Manage APIs Section.
4. Choose Build > Cloud Storage. The Cloud Storage page is displayed. click Enable now.
5. On the page displayed, set Storage instance and Data storage location.Click Next.
{
"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"
}
6 . The Define security rules page is displayed by default.Default security rules allow all reads and writes of authenticated users. In this article we will use default security rules.
7. Cloud Storage is successfully enabled for the project.
8. Make sure Auth Service in Enabled in AGC. Choose Build > Auth Service., click Enable now in the upper right corner. Enable Huawei Account in Authentication mode.
9. Open agconnect-services.json file and add storage-related content to the service tag.
Code:
"cloudstorage":{
"storage_url":"https://ops-dra.agcstorage.link",
"default_storage": "your default storage defined in AGC"
}
Since we have set Data storage location as Singapore, storage URL is https://ops-dra.agcstorage.linkn
If location is set as China, storage location will be https://agc-storage-drcn.platform.dbankcloud.cn
If Location is set as Germany, storage location will be https://ops-dre.agcstorage.link
The value of default_storage is the information entered in the storage instance box on the Project Setting > Build > Cloud Storage page.
10. Add below Permission in AndroidManifest.xml file:
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
11. Add Cloud storage dependencies in app-level build.gradle
Code:
implementation "com.huawei.agconnect:agconnect-storage:1.3.0.300"
12. If app is integrated with Android SDK 29 or later, we also need to add the following attributes under application in AndroidMainfest.xml
Code:
<application
android:name=".EaseMyFlightApplication"
android:allowBackup="false"
android:requestLegacyExternalStorage="true">
13. To initialize cloud storage
Code:
AGCStorageManagement storageManagement = AGCStorageManagement.getInstance();
14. In Flight booking app, we will upload the flight ticket (in pdf format) in cloud storage. Create a reference for the file to be uploaded and enter the file address planned on the cloud.
Code:
StorageReference reference = storageManagement.getStorageReference("Tickets/" + TicketName + “.pdf”);
15. To upload flight ticket
Code:
UploadTask task = reference.putFile(new File("ticket path")); task.addOnFailureListener(new OnFailureListener(){
@Override
public void onFailure(@NonNull Exception exception) {
Log.e(TAG, "Cloud storage file upload failed :" + exception.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.UploadResult>(){
@Override
public void onSuccess(UploadTask.UploadResult uploadResult) {
Log.d(TAG, "Cloud storage file upload success");
}
});
16. To download flight booking ticket from cloud storage
Code:
StorageReference reference = storageManagement.getStorageReference("Tickets/"+ TicketName);
File file = new File(FileUtils.getAppPath(mContext) + TicketName+ ".pdf" );
if(file.exists()) {
file.delete();
}
DownloadTask task = reference.getFile(file);
task.addOnFailureListener(new OnFailureListener(){
@Override
public void onFailure(@NonNull Exception exception) {
exception.printStackTrace();
}
}).addOnSuccessListener(new OnSuccessListener<DownloadTask.DownloadResult>(){
@Override
public void onSuccess(DownloadTask.DownloadResult DownloadResult) {
Intent intent = new Intent(mContext, FlightTicketViewerActivity.class);
intent.putExtra("path", FileUtils.getAppPath(mContext) + fileName+ ".pdf");
mContext.startActivity(intent);
}
}).addOnProgressListener(new OnProgressListener<DownloadTask.DownloadResult>(){
@Override
public void onProgress(DownloadTask.DownloadResult DownloadResult) {
Log.d(TAG, String.format("progress: %f", (DownloadResult.getBytesTransferred()*1.0)/DownloadResult.getTotalByteCount()));
}
}).addOnPausedListener(new OnPausedListener<DownloadTask.DownloadResult>(){
@Override
public void onPaused(DownloadTask.DownloadResult DownloadResult) {
}
});
Screenshots
1. Uploaded flight ticket in AGC console
2. Downloaded ticket in flight booking app
Conclusion
In this article, we have learnt how to upload and download flight ticket using cloud storage. Users flight booking information is stored in App Gallery connect. We will show downloaded flight ticket in Itinerary Activity once user click the flight details from history list.
Reference
Huawei Cloud Storage

Can we store large data into DB.

Related

Samachar a news application using HMS Push Kit Client Side (Part1)

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

Huawei Flight Booking Application (Cloud DB) – Part 8

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 ?

Track Fitness Application using Huawei Health Kit

Overview
Track Fitness application provides users daily step count, calorie burn, how much time user is doing exercise and total distance travelled during that time. Using these real time information, user can keep his fitness record on daily basis and can set a goal towards his fitness. This application uses the Room database for saving the records and displaying in the list. This application uses Huawei Account Kit and Health Kit for login and getting his real time step count. Let us know little about Huawei Health Kit, then we will focus on the implementation part.
Huawei Health Kit
HUAWEI Health Kit provides services for user’s health and fitness data. Using this kit, developers can get real time Step Count, Heart Rate, Body Temperature etc.
Huawei Health Kit provides the following key APIs for the Android client
1) Data Controller: Developers can use this API to insert, delete, update, and read data, as well as listen to data updates by registering a listener.
2) Activity Records Controller: Developers can use this API for tracking daily activity for users like Running, Sleeping etc.
3) Auto Recorder Controller: Developers can use this API to read sensor data in real time like step count.
Integration Started
1) First create an app in AppGallery Connect (AGC).
2) Get the SHA Key. For getting the SHA key, refer this article.
3) Click on Health kit in console.
{
"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"
}
4) Click Apply for Health Kit.
5) Select Product Type as Mobile App, APK Name as your project package name and check the required permission for your application to work, as shown below:
Finally click Submit button to apply for health kit.
6) Check if status is Enabled, as shown in below image.
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 Health Kit, account kit and auth service dependencies in the dependencies section:
Code:
implementation 'com.huawei.hms:base:4.0.0.100'
implementation 'com.huawei.hms:hwid:4.0.0.300'
implementation 'com.huawei.hms:health:5.0.3.300'
10) Enter the dependencies for saving data in Room database.
Code:
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
implementation 'androidx.recyclerview:recyclerview:1.1.0'
11) Add the app ID generated when the creating the app on HUAWEI Developers to manifest file.
Code:
<meta-data
android:name="com.huawei.hms.client.appid"
android:value="Your app id"/>
12) Add the below permissions to manifest file.
Code:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.BODY_SENSORS" />
13) Sync the gradle. Now configuration part completed.
Let us start with the coding part which will explain how to sign in with Huawei id, get authorization access for Health Kit and generate real time step data.
Step 1: Initialize the health service.
Inside activity onCreate() method, call initService().
Code:
private void initService() {
mContext = this;
HiHealthOptions fitnessOptions = HiHealthOptions.builder().build();
AuthHuaweiId signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(fitnessOptions);
mSettingController = HuaweiHiHealth.getSettingController(mContext, signInHuaweiId);
}
Step 2: Huawei Id SignIn and Apply for permissions.
Code:
/**
* Sign-in and authorization method. The authorization screen will display if the current account has not granted authorization.
*/
private void signIn() {
Log.i(TAG, "begin sign in");
List<Scope> scopeList = new ArrayList<>();
// Add scopes to apply for. The following only shows an example. You need to add scopes according to your specific needs.
scopeList.add(new Scope(Scopes.HEALTHKIT_STEP_BOTH)); // View and save step counts in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_HEIGHTWEIGHT_BOTH)); // View and save height and weight in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_HEARTRATE_BOTH)); // View and save the heart rate data in HUAWEI Health Kit.
// Configure authorization parameters.
HuaweiIdAuthParamsHelper authParamsHelper = new HuaweiIdAuthParamsHelper(
HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM);
HuaweiIdAuthParams authParams = authParamsHelper.setIdToken()
.setAccessToken()
.setScopeList(scopeList)
.createParams();
// Initialize the HuaweiIdAuthService object.
final HuaweiIdAuthService authService = HuaweiIdAuthManager.getService(this.getApplicationContext(),
authParams);
// Silent sign-in. If authorization has been granted by the current account, the authorization screen will not display. This is an asynchronous method.
Task<AuthHuaweiId> authHuaweiIdTask = authService.silentSignIn();
// Add the callback for the call result.
authHuaweiIdTask.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() {
@Override
public void onSuccess(AuthHuaweiId huaweiId) {
// The silent sign-in is successful.
Log.i(TAG, "silentSignIn success");
Toast.makeText(GetStartedActivity.this, "silentSignIn success", Toast.LENGTH_SHORT).show();
goToHomeScreen();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception exception) {
// The silent sign-in fails. This indicates that the authorization has not been granted by the current account.
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.i(TAG, "sign failed status:" + apiException.getStatusCode());
Log.i(TAG, "begin sign in by intent");
// Call the sign-in API using the getSignInIntent() method.
Intent signInIntent = authService.getSignInIntent();
// Display the authorization screen by using the startActivityForResult() method of the activity.
// You can change HihealthKitMainActivity to the actual activity.
GetStartedActivity.this.startActivityForResult(signInIntent, REQUEST_SIGN_IN_LOGIN);
}
}
});
}
More details, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0203428726840520025

How Can I Quickly Integrate Cloud Storage of AppGallery Connect into My Cocos-based App?

HUAWEI AppGallery Connect Cloud Storage provides maintenance-free cloud storage functions.Currently, this service is still under beta testing.If you want to quickly experience this service, see the demo on GitHub.
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 Storage in AppGallery Connect
Note: Currently, Cloud Storage 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...Gallery-connect-Guides/agc-cloudstorage-apply
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 Storage, and click Enable now.
{
"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"
}
Configure a storage instance as required.
Define security rules. In this example, the default rules are used.
Note: By default, only authenticated users can read and write data.
3. Integrating the Cloud Storage SDK in Cocos Creator
a. 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 Storage. Currently, the Cloud Storage 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 Storage page, and enable the service.
6. Configure the Default Instance by entering the one set in AppGallery Connect.
b. 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. Preparations for Development
1. Modify the security rules.
Default security rules allow only users authenticated by Huawei to perform operations on cloud storage files.
You can simplify the integration by allowing all users to perform operations without Huawei authentication.
HTML:
// Allow all users.
agc.cloud.storage[
match: /{bucket}/{path=**} {
allow read, write: if true;
}
]
2. Configure the UI layout.
Configure buttons for listing, uploading, downloading, and deleting files separately.
5. Function Development
1. Initialize Cloud Storage and create a listener in the start block.
JavaScript:
start () {
this._storage = huawei.agc.storage;
this._storage.storageService.on("error", data => console.log("Cloud Storage", `error : ${data.errCode}:${data.errMsg}`), this);
this._storage.storageService.on("get-file-metadata", data => console.log("Cloud Storage", JSON.stringify(data)), this);
this._storage.storageService.on("update-file-metadata", data => console.log("Cloud Storage", JSON.stringify(data)), this);
this._storage.storageService.on("delete-file", data => console.log("Cloud Storage", JSON.stringify(data)), this);
this._storage.storageService.on("list-file", data => console.log("Cloud Storage", JSON.stringify(data)), this);
this._storage.storageService.on("get-download-url", data => console.log("Cloud Storage", JSON.stringify(data)), this);
this._storage.storageService.on("task", data => {
console.log("Cloud Storage", JSON.stringify(data));
if (data.task instanceof this._storage.AGCDownloadTask && data.status === 'successful') {
jsb.fileUtils.renameFile(jsb.fileUtils.getWritablePath() + "/output.json", jsb.fileUtils.getWritablePath() + "/output1.json");
}
}, this);
// Create a reference to the root directory.
this.rootReference = huawei.agc.storage.storageService.getInstance().getStorageReference();
},
2. List files.
Use the ListAll method to list all files.
JavaScript:
listAll:function () {
this.rootReference.listAll();
console.log('Cloud Storage', 'ListAll file');
}
3. Download a file.
Download a test.jpg file from the cloud and rename it test1.jpg.
JavaScript:
download:function () {
// Delete the original file before downloading a new one.
jsb.fileUtils.removeFile(jsb.fileUtils.getWritablePath() + "/test.jpg");
this.rootReference.child("test.jpg").getFile(jsb.fileUtils.getWritablePath() + "/test1.jpg");
console.log('Cloud Storage', 'download test.jpg, and reNamed test1.jpg');
},
4. Upload a file.
Upload the downloaded test1.jpg file.
Code:
upload:function () {
if (!jsb.fileUtils.isFileExist(jsb.fileUtils.getWritablePath() + "/test1.jpg")) {
return console.log('Cloud Storage', 'local file test1.jpg not exist, please click Download!')
}
this.rootReference.child("test1.jpg").putFile(jsb.fileUtils.getWritablePath() + "/test1.jpg");
console.log('Cloud Storage', 'upload test1.jpg');
},
5. Delete a file.
Delete the test1.jpg files from both the local path and cloud.
JavaScript:
delete:function () {
this.rootReference.child("test1.jpg").delete();
console.log('Cloud Storage', 'delete test1.jpg success!')
jsb.fileUtils.removeFile(jsb.fileUtils.getWritablePath() + "/test1.jpg");
},
6. Packaging and Testing
In Cocos Creator, go to Project > Build…, package an Android app, install it to your device, and verify the functions.
android:allowBackup=”false”
Note: If you choose the android-30 API, you need to change the value of android:allowBackup to false in the AndroidManifest.xml file.
1. List files.
Click ListAll to view all listed files in the Logcat area. Filter log information by entering Cloud Storage.
2. Download a file.
Click Download and view the result in log information.
3. Upload a file.
Click Upload and view the result in log information.
You can also view the uploaded test1.jpg file in AppGallery Connect.
4. Delete a file.
Click Delete and view the result in log information.
The uploaded test1.jpg file is also deleted in AppGallery Connect.
7. Summary
Cloud Storage allows you to store your Cocos-based game data on the cloud without the hassle of building a server and O&M. Also, with AppGallery Connect, a web console, you can easily manage your files on the cloud side.
In addition to file upload, download, and deletion, Cloud Storage also provides metadata settings.
For more details, please check:
Cloud Storage development guide:
https://developer.huawei.com/consum...-connect-Guides/agc-cloudstorage-introduction
Cocos documentation:
https://docs.cocos.com/creator/manual/en/cocos-service/agc-cloudstorage.html
Is it free?? if it is free is there any limit for size?
Basavaraj.navi said:
Is it free?? if it is free is there any limit for size?
Click to expand...
Click to collapse
Yes, it is free of charge within a certain range, for example, 10 GB storage capacity. For details, see the following link:https://developer.huawei.com/consum...t-Guides/agc-service-billing#h2-1608538047201

Send messages in App! Integrate Huawei In App Messaging services using React Native

{
"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"
}
Introduction
In this article, we will learn how to implement In App Messaging service provided by Huawei. App Messaging of AppGallery Connect to send relevant messages to target users actively using your app to encourage them to use key app functions, or send attractive promotion activities to enhance user loyalty.
Requirements
1. JDK version: 1.7 or later
2. Android Studio version: 3.X or later
3. minSdkVersion: 21 or later
4. targetSdkVersion: 31 (recommended)
5. compileSdkVersion: 29 (recommended)
6. Gradle: 4.1 or later (recommended)
7. Must have a Huawei Developer Account.
8. Must have a Huawei phone with HMS 4.0.0.300 or later and running EMUI 4.0 or later.
9. React Native environment with Android Studio, Node Js and Visual Studio code.
Preparation
1. Create an app or project in the Huawei App Gallery Connect.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the App Messaging API.
3. Download the agconnect-services.json file.
4. Create an Android project.
Integration process
Create a react native project using below command:
Code:
react-native init Project Name
Add below to build.gradle (project) file under buildscript/repositories and allprojects/repositories.
Code:
Maven {url 'http://developer.huawei.com/repo/'}
Add below to build.gradle(app) file, under dependencies to use the App Messaging Sdk.
dependencies{
// Import the App Messaging SDK.
Code:
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.5.1.300'
Note>> to use the Analytics, please add Analytics SDK
Code:
implementation 'com.huawei.hms:hianalytics:5.2.0.300'
}
Add below permissions to manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name= "android.permission.ACCESS_NETWORK_STATE"/>
Open the build.gradle file in the android directory of your React Native project, and change the value of minSdkVersion in buildscript to 19.
Development Process
To make your app's orientation work by default, orientation keywords should be removed from android:configChanges property of the activity tag in AndroidManifest.xml file.
An example of your AndroidManifest.xml is as follows:
Code:
<!-- AndroidManifest.xml. -->
<activity
android:name="com.huawei.agc.rn.appmessaging.example.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Import the following into APP.js file.
Code:
import AGCAppMessaging from '@react-native agconnect/appmessaging';
import {Alert} from 'react-native';
The React Native App Messaging plugin allows you to enable or disable data synchronization from the AppGallery Connect server. The function is enabled by default. The AGCAppMessaging.setFetchMessageEnable API can be called to enable or disable data synchronization from the AppGallery Connect server.
Code:
import AGCAppMessaging from '@react-native-agconnect/appmessaging';
import {Alert} from 'react-native';
AGCAppMessaging.setFetchMessageEnable(true).then(result => {
Alert.alert("[setFetchMessageEnable] " + JSON.stringify(result));
}).catch((err) => {
Alert.alert("[setFetchMessageEnable] Error/Exception: " + JSON.stringify(err));
});
The AGCAppMessaging.setDisplayEnable API can be called to set whether to enable message display.
Code:
import AGCAppMessaging from '@react-native-agconnect/appmessaging';
import {Alert} from 'react-native';
AGCAppMessaging.setDisplayEnable(false).then(result => {
Alert.alert("[setDisplayEnable] " + JSON.stringify(result));
}).catch((err) => {
Alert.alert("[setDisplayEnable] Error/Exception: " + JSON.stringify(err));
});
Add a listener to obtain app message events.
Code:
const eventEmitter = new NativeEventEmitter(AGCAppMessaging);
this.eventListener = eventEmitter.addListener(AGCAppMessaging.EventTypes.ON_MESSAGE_DISPLAY,
(event) => {
Alert.alert("[onMessageDisplay] " + JSON.stringify(event));
console.log("[onMessageDisplay] " + JSON.stringify(event));
})
Call the AGCAppMessaging.setForceFetch API in the testing code to specify that the in-app message data must be obtained from the AppGallery Connect server forcibly.
Sending App Message to our App Users
Choose Your Project in App-Gallery Connect and select the application which you want to test an in-app message of the project.
Choose Grow > App Messaging > New
Enter the information required to send App Messages.
On SELECT SENDING TARGET, Choose your application as Target and click Next.
Select Target users by referring to this document.
Now Set Schedule time and click Next.
Click on OK and then Publish.
Now navigate to Management > Operation column and click Test.
Click Add test user and enter the AAID of the test device in the text box. Click Save.
Now in your APP, Test whether the message can be properly displayed and operated.
Output
You can check the action in your console log
Tips and Tricks
1. Set minSdkVersion to 19 or higher.
2. To view the events of App Messaging, Huawei Analytics needs to be enabled and configured.
Conclusion
In this article, we have learned how to integrate IN APP Messaging service by Huawei. APP Messages are very useful for delivering the right message to the target user. It encourages them to use key app functions, or send attractive promotion activities to enhance user loyalty.
Reference
In App Messaging: Documentation
In App Messaging : Training Video

Categories

Resources