Tic Tac Toe Game using HTML5 Quick Game - Part 2 - Huawei Developers

{
"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 my last article, we can learn the following:
What is Quick game?
Feature and advantage of Quick game.
Development procedure.
Installing development tools.
If you have not yet read my previous article read it here to understand more about quick game. Just to summarize in my previous article we have installed project and created the application in Quick app IDE.
In this article, we can learn the following:
Creating Quick Game.
Generating and configuring a certificate fingerprint.
Enabling Game service and Account kit.
Creating Quick Game
Step 1: Sign in to AppGallery Connect and click My apps.
Step 2: Click New App.
Step 3: Add all required information, then click OK.
Parameters information
Step 4: Navigate to project setting > General information add package details.
Step 5: Add Default data processing location.
Generating and configuring a certificate fingerprint.
Create certificate
Step 1: Open Quick App IDE and open an existing project or create new project.
Step 2: Choose Tools > Certificate
Step 3: If signature is not yet created, select Create else if already exist select Import.
Step 4: Add necessary information and click Create.
Step 5: Copy SHA-256 certificate fingerprint from output.
Configure the Certificate fingerprint in AppGallery
Step 1: Sign in to AppGallery and click My project
Step 2: Select the project which you want to configure the certificate fingerprint.
Step 3: Navigate to Project Settings > General information in the App information and enter the copied SHA-256 certificate.
Enable Game service.
Step 1: Sign in to AppGallery and click My project.
Step 2: Select the project which you want to enable Game service and account kit.
Step 3: Navigate to Project Settings > Manage API and enable account kit and Game service.
Build the HTML5 Quick Game
HTML:
<!-- HTML5 Quick Game Access Guidance -->
<!-- https://developer.huawei.com/consumer/en/doc/development/quickApp-Guides/quickgame-develop-h5-game-->
<template>
<div class="doc-page">
<!-- Replace the link to the HTML5 game -->
<web class="web-page" src="{{gameUrl}}" type="game" trustedurl="{{list}}" onpagestart="onPageStart"
fullscreendirection="{{fullscreenDirection}}" jumppolicy="{{linkJumpPolicy}}" multiwindow="{{openMultiwindow}}"
onpagefinish="onPageFinish" ontitlereceive="onTitleReceive" onerror="onError" id="web"
allowthirdpartycookies="{{allowThirdPartyCookies}}">
</web>
</div>
</template>
<style>
.doc-page {
flex-direction: column;
flex-direction: column;
justify-content: center;
align-content: center;
align-items: center;
}
.web-page {
width: 100%;
height: 100%;
}
</style>
<script>
import router from "@system.router"
import prompt from '@system.prompt'
export default {
props: ['websrc'],
data: {
title: "",
// TODO Replace the link to the H5 game
gameUrl: "https://codepen.io/timrijkse/full/XjLGKv/",
// Attribute allowthirdpartycookies, indicates whether cookies can be delivered in cross-domain mode.
// If you need login Google Account or Other Account, Please set TRUE.
allowThirdPartyCookies: true,
//Attribute fullscreendirection,controls the direction when the webpage requests full screen.
//If you want the full screen orientation to be vertical, please set it to portrait.
//The default value is landscape
fullscreenDirection: "landscape",
//If you want the ads in the game to be opened in the browser, please set the value of openMultiwindow
// to true and the value of linkJumpPolicy to browser
linkJumpPolicy: "default",
openMultiwindow: false,
// Here the trust list settings, when the loading page has multiple addresses, such as the successful loading of the login address and the inconsistent entry address, it needs to set the trust list to do so.
list: ["new RegExp('https?.*')"],
},
onPageStart(e) {
console.info('pagestart: ' + e.url)
},
// Each page switch triggers
onPageFinish(e) {
console.info('pagefinish: ' + e.url, e.canBack, e.canForward)
},
onTitleReceive(e) {
this.title = e.title;
},
onError(e) {
console.info('pageError : ' + e.errorMsg)
},
onMessage(e) {
console.info('onmessage e = ' + e.message + ", url = " + e.url);
prompt.showToast({
message: e.message + ': ' + e.url
})
},
isCanForward() {
this.$element('web').canForward({
callback: function (e) {
if (e) {
this.$element('web').forward();
}
}.bind(this)
})
},
isCanBack() {
this.$element('web').canBack({
callback: function (e) {
if (e) {
this.$element('web').back();
} else {
router.back();
}
}.bind(this)
})
},
onShow: function () {
console.info(" onshow");
},
onHide: function () {
console.info(" onHide");
},
onBackPress() {
const prompt = require('@system.prompt')
prompt.showDialog({
message: 'Whether to quit the html5 game?',
buttons: [
{
text: 'Cancel'
},
{
text: 'Exit'
}
],
success: (data) => {
console.log('handling callback', data.index)
if (data.index === 1) {
this.$app.exit()
}
},
cancel: function () {
console.log('handling cancel')
},
fail: function (data, code) {
console.log(`handling fail, code = ${code}`)
}
})
return true
},
}
</script>
Result
Tips and Tricks
Understand About Quick Game.
Explore some Quick Game from phone.
Install all the required tools.
Make sure you have configured the adb in the desktop or laptop.
Command to install Quick App loader APK is adb install quickapploader.apk
Enable Game service and account kit.
Conclusion
In this article, we have learnt about creating Quick Game, generating and configuring the SHA-256 fingerprint certificate, Enabling game service and account kit and building HTML5 Quick Game application.
Reference
Quick Game official document
Download tools from here
Beginner: Find the Explanation of Quick Game Part 1

thanks for sharing

Related

Integrate Ads kit in Flutter Application

More articles like this, you can visit HUAWEI Developer Forum
In this article we will be working on HMS Ads kit and integrate into a flutter application.
In first part we will work on the setup part and in second part we will work on implementing the ads in application.
Step 1: Create a project in AGC console
Step 2: You have to install flutter and dart plugin to android studio. Go to File -> Settings -> Plugins
{
"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"
}
Once both are installed it will show you an option to create a new project in flutter.
To confirm run the below command in terminal “flutter doctor”
If you are still facing any issue in setup please comment below and I will make sure to resolve them.
Step 3: Download the folder and add in in your workspace where your flutter project resides.
https://developer.huawei.com/consumer/en/doc/HMS-Plugin-Library-V1/flutter-sdk-download-0000001050196675-V1
Step 4: Open pubspec.yaml file and add the below code.
Code:
huawei_ads:
path: ../huawei_ads/
..means to go 2 step backwards in folder and Huawei_ads is the folder name which you downloaded in previous step.
Once you change the pubspec.yaml file it will ask you to get the dependencies.
Click on pub get button highlighted above and you can get the latest dependencies.
Below message should be shown if the step goes successful.
To confirm the above step is successful you can also open external libraries and check flutter plugin added to it.
Step 5: Open the android project level gradle file and add below code.
Code:
dependencies {
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
}
add below code in buildscript and allprojects section of gradle file
Code:
maven { url 'https://developer.huawei.com/repo/' }
Step 6: Go to app level gradle file and add below dependencies and agc services
Code:
implementation 'com.huawei.hms:ads-lite:13.4.30.301'
implementation 'com.huawei.hms:ads-consent:3.4.28.305'
implementation 'com.huawei.hms:ads-identifier:3.4.28.313'
implementation 'com.huawei.hms:ads-installreferrer:3.4.28.313'
Code:
apply plugin: 'com.huawei.agconnect'
Step 7: Add the agconnect-services.json into android -> app folder
Till here your initial setup is completed.
Now you have to create a UI where you can showcase your ads.
I am using a RaisedButton in order to call the logic of ads creation. You can use your own triggering mechanism in order to show the ads.
Banner Ads:
Code:
import 'package:flutter/material.dart';
import 'package:huawei_ads/hms_ads_lib.dart';
class BannerAds extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.topCenter,
child: RaisedButton(
child: Text(
'Load Banner Ads',
),
onPressed: () {
BannerAd _bannerAd = createBannerAd();
_bannerAd
..loadAd()
..show();
},
),
);
}
}
BannerAd createBannerAd() {
return BannerAd(
adUnitId: "testw6vs28auh3",
size: BannerAdSize(width: 360, height: 57),
adParam: AdParam.build(),
);
}
Make sure you use the proper imports
Create a method which returns BannerAd
I am using test add id but you can use your own add id.
I am showcasing with 2 banner size but you can modify them according to your need.
Call the load add and show add method to show the banner ad.
Below is the table from which you can choose ad size.
Below are the screenshot for Banner Ads
Splash Ads:
Code:
import 'package:flutter/material.dart';
import 'package:huawei_ads/hms_ads_lib.dart';
class SplashAds extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.topCenter,
child: RaisedButton(
child: Text(
'Load Splash Ads',
),
onPressed: () {
SplashAd splashAd = createSplash();
splashAd
..loadAd(
adUnitId: "testq6zq98hecj",
orientation: SplashAdOrientation.portrait,
adParam: AdParam.build(),
topMargin: 1);
},
),
);
}
}
SplashAd createSplash() => SplashAd(
adType: SplashAdType.above,
ownerText: 'Owner Text',
footerText: 'Footer Text',
loadListener: (SplashAdLoadEvent event, {int errorCode}) {
print("SplashAdLoadEvent : $event");
if (event == SplashAdLoadEvent.dismissed) {
//Handle Dismiss logic here
}
});
Create a method which returns SplashAd
I am using test add id but you can use your own add id.
topMargin can increase the margin space between splash and top border.
You can also define the orientation of add as well.
You can customize Owner text and Footer Text.
Below are the screenshot for Splash Ads
Interstitial Ads
Code:
import 'package:flutter/material.dart';
import 'package:huawei_ads/adslite/interstitial/interstitial_ad.dart';
class InterstitialAds extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.topCenter,
child: RaisedButton(
child: Text(
'Load Interstitial Ads',
),
onPressed: () {
InterstitialAd _interstitialAd = createInterstitialAd();
_interstitialAd
..loadAd()
..show();
},
),
);
}
}
InterstitialAd createInterstitialAd() {
return InterstitialAd(
adUnitId: "teste9ih9j0rc3",
);
}
Create a method which returns Interstitial Ad
I am using test add id but you can use your own add id.
Below are the screenshot for Interstitial Ad.
I hope you with the above snippets you can implement above three categories of ads.

Great way to test android apps[HMS and GMS], A/B Testing

More information about this, you can visit HUAWEI Developer Forum
​Introduction
This article will guide you to use A/B testing in android project. It will provide details to use HMS and GMS.
Steps
1. Create App in Android
2. Configure App in AGC
3. Integrate the SDK in our new Android project
4. Integrate the dependencies
5. Sync project
Procedure
Step1: Create application in android studio.
HMS related dependencies, Add below dependencies in app directory
Code:
implementation 'com.huawei.agconnect:agconnect-remoteconfig:1.3.1.300'
apply plugin:'com.huawei.agconnect'
Add below dependencies in root directory
Code:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
GMS related dependencies, Add below dependencies in app directory
Code:
implementation 'com.google.android.gms:play-services-analytics:17.0.0'
implementation 'com.google.firebase:firebase-config:19.2.0'
Add below dependencies into root directory
Code:
classpath 'com.google.gms:google-services:4.3.3'
Step2: Create MobileCheckService class, using this class you can identify whether the device has HMS or GMS.
Code:
class MobileCheckService {
fun isGMSAvailable(context: Context?): Boolean {
if (null != context) {
val result: Int = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
if (com.google.android.gms.common.ConnectionResult.SUCCESS === result) {
return true
}
}
return false
}
fun isHMSAvailable(context: Context?): Boolean {
if (null != context) {
val result: Int = HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context)
if (com.huawei.hms.api.ConnectionResult.SUCCESS == result) {
return true
}
}
return false
}
}
Step3: Create instance for Mobilecheckservice inside activity class. Inside OnCreate() call checkAvailableMobileService().This method return whether the device has HMS or GMS.
Code:
private fun checkAvailableMobileService() {
if (mCheckService.isHMSAvailable(this)) {
Toast.makeText(baseContext, "HMS Mobile", Toast.LENGTH_LONG).show()
configHmsTest()
} else
if (mCheckService.isGMSAvailable(this)) {
Toast.makeText(baseContext, "GMS Mobile", Toast.LENGTH_LONG).show()
configGmsTest()
} else {
Toast.makeText(baseContext, "NO Service", Toast.LENGTH_LONG).show()
}
}
Step4: If the device support HMS, then use AGConnectConfig.
Code:
private fun configHmsTest() {
val config = AGConnectConfig.getInstance()
config.applyDefault(R.xml.remote_config_defaults)
config.clearAll()
config.fetch().addOnSuccessListener { configValues ->
config.apply(configValues)
config.mergedAll
var sampleTest = config.getValueAsString("Festive_coupon")
Toast.makeText(baseContext, sampleTest, Toast.LENGTH_LONG).show()
}.addOnFailureListener { Toast.makeText(baseContext, "Fetch Fail", Toast.LENGTH_LONG).show() }
}
Step5: If the device support GMS, then use FirebaseRemoteConfig.
Code:
private fun configGmsTest() {
val firebase = FirebaseRemoteConfig.getInstance();
val configSettings = FirebaseRemoteConfigSettings.Builder().build()
firebase.setConfigSettingsAsync(configSettings)
firebase.setDefaultsAsync(R.xml.remote_config_defaults)
firebase.fetch().addOnCompleteListener { configValues ->
if (configValues.isSuccessful) {
firebase.fetchAndActivate()
var name = firebase.getString("Festive_coupon")
Toast.makeText(baseContext, name, Toast.LENGTH_LONG).show()
} else {
Toast.makeText(baseContext, "Failed", Toast.LENGTH_LONG).show()
}
}
}
App Configuration in Firebase:
Note: A/B test is using HMS configuration, refer
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201248355275100167&fid=0101187876626530001
Step1: To configure app into firebase Open firebase https://console.firebase.google.com/u/0/?pli=1
{
"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"
}
Step2: Click Add Project and add required information like App Name, package name, SHA-1.
Step3: After configuration is successful, then click A/B Testing in Grow menu.
To Start A/b testing experiment Click Create experiment button, It will show you list of supported experiments. Using Firebase you can do three experiments.
· Notifications
· Remote Config
· In-App Messaging
Notification: This experiment will use for sending messages to engage the right users at the right moment.
Remote Config: This experiment will use to change app-behavior dynamically and also using server-side configuration parameters.
In-App Messaging: This experiment will use to send different In-App Messages.
Step4: Choose AbTesting > Remote Config > Create a Remote Config experiment, provide the required information to test, as follows
Step5: Choose AbTesting > Remote Config > App_Behaviour, following page will display.
Step6: Click Start experiment, then start A/B test based on the experiment conditions it will trigger
Step7: After successful completion of experiment, we can get report.
Conclusion:
Using A/B test, you can control the entire experiment from HMS or GMS dashboard, this form of testing will be highly effective for the developers.
Reference:
To know more about firebase console, follow the URL https://firebase.google.com/docs/ab-testing
Share your thoughts on this article, if you are already worked with A/B tests, then you can share your experience on separation between them with us

Ads Kit Integration with Cocos

1. Cocos Creator tool
2. Notepad++ for editing and writing script
3. HMS Device
4. Android Studio for Analyzing APK and Checking Log
1. Install and launch cocos creator.
2. Make sure to configure NDK Root and Android SDK Root in Cocos Creator, choose File> Settings>Select Native Develop.
In the same build popup, In the keystore section we can use default keystore (default location is /Users/<username>/.android/debug.keystore) and we can generate SHA key or we can create custom keystore and can generate SHA key.
In Command line terminal execute the command below and get SHA key:
Code:
keytool -list -v -keystore keystorepath\keystorename.keystore
4. Step 1: Create a project in AppGallery using created SHA key
Step 2: Configure the signing certificate fingerprint
Choose Project settings > General information. In the App information area, click the icon next to SHA 256 certificate fingerprint, and enter the obtained SHA-256 certificate fingerprint.
Step 3: Download agconnect-services.json file and put in setting folder in cocos project.
Example:
Right click on Assets folder and then select Open in explorer and
{
"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"
}
And put agconnect-services.json file inside settings folder
5. Click Enable for Cocos SDKHub in Service tab.
Click on association button and register project in Cocos Console
Associating a Game in Cocos Creator
You can enable third-party services for your app in Cocos Creator. But first, you need to set a Cocos AppID. Select a created game, and click Association, as shown in the following figures.
Select Ads option in Plugin Manager under Service tab.
Place mouse cursor over the "Configured" text so that "Edit" and "Delete" icons will be appeared. Click on edit icon and put public key(from AppGallery connect) in the "Payment Public key" field and select "en" option for "Support language" field and then click OK.
Code:
invokeBannerAds()
{
var params = { "adType": "Banner", "adId": "testw6vs28auh3", "pos": "0", "adSize": "BANNER_SIZE_320_50" };
sdkhub.getAdsPlugin().showAds(params);
},
invokepreloadrewardAds()
{
var params = { "adType": "Reward", "adId": "testx9dtjwj8hp" };
sdkhub.getAdsPlugin().preloadAds(params);
},
invokeRewardAds()
{
var params = { "adType": "Reward", "adId": "testx9dtjwj8hp" };
sdkhub.getAdsPlugin().showAds(params);
},
invokeNativeAdfull()
{
var params = { "adType": "Native", "adId": "testy63txaom86", "nativeLayout": "native_full", "requestCustomDislikeThisAd": "1", "choicesPosition": "3", "videoConfiguration" : "1", "audioFocusType" : "NOT_GAIN_AUDIO_FOCUS_WHEN_MUTE", "startMuted" : "0", "customizeOperateRequested" : "1"};
sdkhub.getAdsPlugin().showAds(params);
},
invokeNativeAd()
{
var params = { "adType": "Native", "adId": "testy63txaom86", "nativeLayout": "native_small", "requestCustomDislikeThisAd": "1", "choicesPosition": "3", "videoConfiguration" : "1", "audioFocusType" : "NOT_GAIN_AUDIO_FOCUS_WHEN_MUTE", "startMuted" : "0", "customizeOperateRequested" : "1"};
sdkhub.getAdsPlugin().showAds(params);
},
invokepreIntertitialsAds()
{
var params = { "adType": "Interstitial", "adId": "testb4znbuh3n2" }; sdkhub.getAdsPlugin().preloadAds(params);
},
invokeIntertitialsAds()
{
var params = { "adType": "Interstitial", "adId": "testb4znbuh3n2" };
sdkhub.getAdsPlugin().showAds(params);},
Banner Ad
Native Ad small
Native Ad Full
Reward Ad
Interstitial Ad
Tips and Tricks
1. Make sure to keep the same package name as kept in the Huawei AppGallery Connect project.
2. Both rewarded ads and interstitial ads need to call preloadAds first, and then call showAds afte receiving successful callback. Banner ads can directly call showAds
Conclusion:
HUAWEI Ads Service is a monetization service that leverages Huawei’s extensive data capabilities to display targeted, high quality ad content in your apps to the vast user base of Huawei devices.
References:
https://docs.cocos.com/creator/manual/en/cocos-service/sdkhub-plugins/sdkhub-hms.html
https://developer.huawei.com/consumer/en/hms/huawei-iap/
Hi, this topic is regarding HMS Ads Service, but you given In-App-Purchase link in reference.
Great news!
Good new Incoming about Huawei

How Can I Quickly Integrate AppGallery Connect Auth Service into a Web App?

Currently, AppGallery Connect Auth Service also supports web apps. I have integrated the service by referring to the official documentation. You can also download the sample code for reference. I’ll show you the simple procedure in this post.
Integration Procedure​1.Enabling the Service
a) Create a web app in AppGallery Connect.
{
"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"
}
b) Enable Auth Service.
c) Enable the Anonymous account, Mobile number, and Email address authentication modes.
2. Integrating the AppGallery Connect SDK
a) Add the configuration code to the login.vue file.
b) In Huawei Quick App IDE, open your quick app project, integrate the AppGallery Connect JavaScript SDK to your project, and import the module for Auth Service.
3. Implementing Functions
a) For anonymous accounts:
Add a button for anonymous sign-in to your test app and click the button. The sample code is as follows:
JavaScript:
loginAnonymously() {
console.log("JS-SDK login anonymously!");
agconnect.auth().signInAnonymously().then(user => {
// Sign-in successful.
alert("loginAnonymously successfully");
this.getUserInfo();
}).catch(error => {
// Sign-in error.
alert(error)
});
},
When the anonymous sign-in is successful, a UID is displayed.
b) For mobile phone numbers or email addresses (password mode):
Add a text box for users to input the mobile phone number or email address and a text box for the password input to your test app. Input required information to sign in to the app. The sample code is as follows:
JavaScript:
loginByPwd() {
console.log("JS-SDK auth(): login...")
let credential = null;
if (this.dataForm_sdk.password == '') {
alert("Please typein password!");
return;
}
switch (this.provider) {
case 'phone':
credential = agconnect.auth.PhoneAuthProvider.credentialWithPassword('86', this.dataForm_sdk.account, this.dataForm_sdk.password);
break;
case 'email':
credential = agconnect.auth.EmailAuthProvider.credentialWithVerifyCode(this.dataForm_sdk.account, this.dataForm_sdk.password);
break;
default:
break;
}
if (credential == null) {
console.log("credential null!");
return;
}
agconnect.auth().signIn(credential).then(res => {
alert("Sign-in successful.");
this.getUserInfo();
}).catch(err => {
alert(err);
});
},
c) For mobile phone numbers or email addresses (verification code mode):
Add a text box for users to input the mobile phone number or email address and a button for obtaining a verification code to your test app. Input required information and click the button to obtain the verification code. The sample code is as follows:
JavaScript:
getVerifyCode() {
console.log("request for email verifycode...")
this.dataForm_sdk.verifyCode = '';
switch (this.provider) {
case 'phone':
// Obtain a verification code.
agconnect.auth.PhoneAuthProvider.requestVerifyCode('86', this.dataForm_sdk.account,agconnect.auth.Action.ACTION_REGISTER_LOGIN, 'zh_CN', 90).then(ret => {
alert("Request sent.");
}).catch(error => {
alert("Request failed.");
});
break;
case 'email':
agconnect.auth.EmailAuthProvider.requestVerifyCode(this.dataForm_sdk.account, agconnect.auth.Action.ACTION_REGISTER_LOGIN, 'zh_CN', 120).then(ret => {
// Request sent.
alert("Request successful.");
}).catch(error => {
// Request failed.
alert(error)
});
break;
default:
break;
}
},
Add a button for sign-in using a verification code. The sample code is as follows:
JavaScript:
loginByVerifyCode() {
if (this.dataForm_sdk.verifyCode == '') {
alert("Enter the verification code.");
return;
}
let credential = null;
switch (this.provider) {
case 'phone':
credential = agconnect.auth.PhoneAuthProvider.credentialWithVerifyCode('86', this.dataForm_sdk.account, this.dataForm_sdk.password, this.dataForm_sdk.verifyCode);
break;
case 'email':
credential = agconnect.auth.EmailAuthProvider.credentialWithVerifyCode(this.dataForm_sdk.account, this.dataForm_sdk.password, this.dataForm_sdk.verifyCode);
break;
case 'QQ':
break;
case 'weChat':
break;
default:
break;
}
if (credential == null) {
console.log("credential null!")
return;
}
agconnect.auth().signIn(credential).then(res => {
alert("Sign-in successful.");
this.getUserInfo();
}).catch(err => {
alert(err);
});
},
Summary
AppGallery Connect Auth Service provides quite a lot of authentication modes and the integration is simple to complete.
If you have any other questions, please check the official demo.

Shares the user's credentials between your Android apps, quick apps and web apps using Huawei Keyring

Introduction
In this article, we will build two applications App1 and App2. And Shares the user's credentials between App1 and App2.
Keyring offers the Credentials Management API for storing user credentials locally on Android phones and tablets and sharing them between different apps and different platform versions of an app.
Shares the user's credentials between your Android apps, quick apps and web apps.
Credential Management Services
Secure local storage of user credentials
Your app stores a signed-in user's credentials in Keyring for automatic sign-in later. Keyring encrypts the credentials and stores them on the user's device. When storing credentials, you can set whether to verify the user's biometric feature or lock screen password when an app tries to access the stored credentials.
When the user opens your app next time, it will search Keyring for the available credentials, which may be those stored in this app or those from other apps and shared for this app to access.
Credential sharing
If you have multiple apps, you can share credentials stored on one app to other apps. Once a user signs in to this app, all the other apps can conveniently use the credentials from this app to sign the user in.
When storing credentials, you can set the sharing relationship of the credentials and share the credentials stored on one app to other apps. The credentials can be shared between Android apps, quick apps and web apps.
Prerequisites
JDK version: 1.7 or later
Android Studio version: 3.6.1 or later
minSdkVersion: 24 or later
targetSdkVersion: 30 (recommended)
compileSdkVersion: 30 (recommended)
Gradle version: 5.4.1 or later (recommended)
Test device: a Huawei phone running EMUI 5.0 or later
How to integrate Huawei Keyring in Android?
To achieve this you need to follow the steps.
1. Configure application on the AGC.
2. Client application development process.
Configure application on the AGC
Follow the steps.
Step 1: We need to register as a developer account in AppGallery Connect. If you are already developer ignore this step.
Step 2: Create an app by referring to Creating a Project and Creating an App in the Project
Step 3: Set the data storage location based on current location.
Step 4: Enabling Keyring Kit. Project setting > Manage API > Enable Keyring kit toggle button.
{
"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"
}
Step 5: Generating a Signing Certificate Fingerprint.
Step 6: Configuring the Signing Certificate Fingerprint.
Step 7: Download your agconnect-services.json file, paste it into the app root directory.
Client application development process
Follow the steps.
Step 1: Create Android application in the Android studio (Any IDE which is your favorite)
Step 2: Add the App level gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation "com.huawei.hms:keyring-credential:6.1.1.302"
}
Root level gradle dependencies.
maven { url 'https://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: Build Application.
Application 1
Java:
private fun checkInput(): Boolean {
val username = mUsername!!.text.toString().trim { it <= ' ' }
val password = mPassword!!.text.toString().trim { it <= ' ' }
return if (username.isEmpty() || password.isEmpty()) {
showMessage(R.string.invalid_input)
false
} else {
true
}
}
private fun login(view: View) {
if (!checkInput()) {
return
}
val username = mUsername!!.text.toString().trim { it <= ' ' }
val password = mPassword!!.text.toString().trim { it <= ' ' }
saveCredential(username, password,
"app2", "com.huawei.hms.keyring.sample2",
"3E:29:29:33:68:91:28:FF:58:54:B7:1D:1B:B3:9E:61:AD:C8:32:78:A3:81:B0:E2:9A:9E:35:6E:02:5D:2E:FB",
true)
}
private fun saveCredential(username: String, password: String,
sharedToAppName: String, sharedToAppPackage: String,
sharedToAppCertHash: String, userAuth: Boolean) {
val app2 = AndroidAppIdentity(sharedToAppName,
sharedToAppPackage, sharedToAppCertHash)
val sharedAppList: MutableList<AppIdentity> = ArrayList()
sharedAppList.add(app2)
val credential = Credential(username, CredentialType.PASSWORD, userAuth, password.toByteArray())
credential.setDisplayName("nickname_" + username)
credential.setSharedWith(sharedAppList)
credential.syncable = true
val credentialClient = CredentialManager.getCredentialClient(this)
credentialClient.saveCredential(credential, object : CredentialCallback<Void?> {
override fun onSuccess(unused: Void?) {
showMessage(R.string.save_credential_ok)
}
override fun onFailure(errorCode: Long, description: CharSequence) {
showMessage(R.string.save_credential_failed.toString() + " " + errorCode + ":" + description)
}
})
}
private fun deleteCredential(credential: Credential) {
val credentialClient = CredentialManager.getCredentialClient(this)
credentialClient.deleteCredential(credential, object : CredentialCallback<Void?> {
override fun onSuccess(unused: Void?) {
val hint = String.format(resources.getString(R.string.delete_ok),
credential.getUsername())
showMessage(hint)
}
override fun onFailure(errorCode: Long, description: CharSequence) {
val hint = String.format(resources.getString(R.string.delete_failed),
description)
showMessage(hint)
}
})
}
private fun delete(view: View) {
val username = mUsername!!.text.toString().trim { it <= ' ' }
if (username.isEmpty()) {
return
}
val credentialClient = CredentialManager.getCredentialClient(this)
val trustedAppList: List<AppIdentity> = ArrayList()
credentialClient.findCredential(trustedAppList, object : CredentialCallback<List<Credential>> {
override fun onSuccess(credentials: List<Credential>) {
if (credentials.isEmpty()) {
showMessage(R.string.no_available_credential)
} else {
for (credential in credentials) {
if (credential.getUsername() == username) {
deleteCredential(credential)
break
}
}
}
}
override fun onFailure(errorCode: Long, description: CharSequence) {
showMessage(R.string.query_credential_failed)
}
})
}
Result​
Tips and Tricks​
Add the agconnect-service.json.
Make sure you are testing application in non-rooted device.
Latest HMS Core APK is required.
Set minSDK 24 or later.
Find all result code here
It also support non Huawei phones but android version should be 7 or later.
Conclusion​
In this article, we have learnt integration of Huawei Keyring. Sharing the password between two applications. And credential management services. Sign in with different application using single stored password.
Reference​
Keyring

Categories

Resources