Unity & HMS account kit integration.
In this article, we will integrate HMS account kit with Unity. We will perform Login & Logout.
Requirements ->
Unity Editor
Huawei device
Visual Studio
Output --> Upon succeful login User will get display name and other details, On UI i am populating DisplayName like below.
{
"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 1 Create Unity 3d project
Step 2 Register project on HMS Console as Game.
(Dont forget to put SHA key from keystore file)
Step 3 Collect below information
Step 4 Download HMS Unity Plugin (HMS Unity Plugin v1.1.2) from
Code:
https://github.com/EvilMindDevs/hms-unity-plugin/releases
Step 5 Import this plugin in Unity project like show below
Step 6 Additoinal Configuration using HMS Plugin, click on Huawei -> App Gallery
Step 7
in step 3 we collected information which we need to fill here in Huawei Plugin Editor, like show below
Step 8 Once information is filled a button will appear "Configure Manifest", click on that and close editor
Step 9 Verify details in manifest file, you can find this file in below location
Assets -> Plugins -> Android -> AndroidManifest.xml
We need to verify above filled details in this file like show below
Step 10 Update & Verify package name like below
File -> BuildSettings -> Android -> Player Settings -> Other Settings
Step 11 Install Unity Remote apk in your huawei device for running and debugging project
Please use custom keystore
Build the project and try to run -> if it gives error like manifest merger failed, which i got, open manifest file in text editor and fix it, if it has duplicate providers, once done you can see ur project running in huawei device
Step 12 HMS Plugin apis will be available as soon as prefab is added to the scene like below
Where to find prefab -> Assets -> Huawei -> Prefabs
Step 13 Scripting
I am going to create 2 scripts, both are conncted on my Player (U can connect on any element)
PlayerController - I used this to initalize HMS Account Kit
UpdateDetails - to update user name on canvas received from HMS account service.
PlayerController.cs
Code:
using System.Collections;
using System.Collections.Generic;
using HmsPlugin;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float runSpeed;
Rigidbody myRb;
Animator myAnim;
bool facingRight;
private AccountManager accountManager;
UpdateDetails updateDetails;
// Start is called before the first frame update
void Start()
{
updateDetails = GetComponent<UpdateDetails>();
myRb = GetComponent<Rigidbody>();
myAnim = GetComponent<Animator>();
facingRight = true;
accountManager = AccountManager.GetInstance(); // Initialization of account manager
accountManager.OnSignInSuccess = OnLoginSuccess;
accountManager.OnSignInFailed = OnLoginFailure;
Debug.LogWarning("kamal Start");
accountManager.SignIn(); // login
}
public void OnLoginSuccess(HuaweiMobileServices.Id.AuthHuaweiId authHuaweiId)
{
//loggedInUser.text = string.Format(LOGGED_IN, authHuaweiId.DisplayName);
Debug.LogWarning("kamal OnLoginSuccess-->"+ authHuaweiId.DisplayName);
updateDetails.updateUserName("Welcome "+authHuaweiId.DisplayName);
}
public void OnLoginFailure(HuaweiMobileServices.Utils.HMSException error)
{
//loggedInUser.text = LOGIN_ERROR;
Debug.LogWarning("kamal OnLoginSuccess");
updateDetails.updateUserName("error in login-- " + error.Message);
}
// Update is called once per frame
void Update()
{
}
}
UpdateDetails.cs -> update details on UI Canvas
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UpdateDetails : MonoBehaviour
{
public Text userName;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void updateUserName(string name) {
Debug.LogWarning("kamal updateUserName-->" + name);
userName.text = name;
}
}
Result -> User name is shown on UI after login using HMS account kit.
What about Logout -> User below code snipped
Code:
accountManager.SignOut();
Nice article
I am not able to retreive email id of user once successful login, it gives me null. what might be the reason
Related
More information, you can visit HUAWEI Developer Forum.
Huawei Share capabilities are open to all apps. They can be seamlessly embedded into the sharing logic of apps that integrate HUAWEI Share Kit, creating a consistent UI for sharing across app. Apps can open the Huawei Share page using the Intent method and call the Huawei Share APIs. For details, see the Huawei Share to Become Available in Apps.
Read on to find out how to quickly integrate HUAWEI Share Kit into phone apps.
Step 1: Configuring files
Because the demo runs on a Huawei phone which has integrated Huawei Share, it does not need to integrate the Share Kit SDK.
1. Configure the build.gradle file for your app:
Code:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.aar'])
implementation 'com.android.support:support-compat:28.0.0'
}
2. Change the minSdkVersion value in the file to 26.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
3. Click the sync button to synchronize the project.
Step 2: Integrating and developing functions
1. Share text content.
Code:
private void doStartTextIntent() {
String text = shareText.getText().toString();
if (TextUtils.isEmpty(text)) {
return;
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(SHARE_INTENT_TYPE);
intent.putExtra(Intent.EXTRA_TEXT, "test text");
intent.setPackage(SHARE_PKG);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PackageManager manager = getApplicationContext().getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
if (infos.size() > 0) {
// size == 0 indicates that the current device does not support Intent-based sharing.
getApplicationContext().startActivity(intent);
}
}
2. Share files.
Code:
private void doStartFileIntent() {
String text = shareText.getText().toString();
if (TextUtils.isEmpty(text)) {
return;
}
ArrayList<Uri> uris = getFileUris(text);
if (uris.isEmpty()) {
return;
}
Intent intent;
if (uris.size() == 1) {
// Shares one file.
intent = new Intent(Intent.ACTION_SEND);
intent.setType(SHARE_INTENT_TYPE);
intent.putExtra(Intent.EXTRA_STREAM, uris.get(0));
intent.setPackage(SHARE_PKG);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
// Shares multiple files.
intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType(SHARE_INTENT_TYPE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
intent.setPackage(SHARE_PKG);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
PackageManager manager = getApplicationContext().getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
if (infos.size() > 0) {
// size == 0 indicates that the current device does not support Intent-based sharing.
getApplicationContext().startActivity(intent);
}
}
HUAWEI Share Kit is now integrated. But before you get started, make sure you have the following:
· Two Huawei phones running EMUI 9.0 or later for debugging, one which can be used as the sender, and the other which can be used as the receiver
· Java JDK (1.8 or later).
· Android API (level 26 or higher).
· Android Studio development environment: V3.0.1 or later is recommended
For more information about integrating HUAWEI Share Kit into Huawei phone apps, see the Preparations for Integrating HUAWEI Share Kit into Huawei Phone Apps.
For more information about HUAWEI Share Kit, visit HUAWEI Developers.
Recommended reading:
Share Kit | Fully-Open HUAWEI Linux Share Kit Unveiled, Allowing for File Transfers Between Huawei and Linux Devices
Fully-Open HUAWEI Windows Share Kit Unveiled, Offering a New Paradigm for Phone-PC File Transfers
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
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
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
Xamarin (Microsoft) is a multi-system development platform for mobile services that many developers use. Many AppGallery Connect services now support Xamarin, including Auth Service. Here I’ll explain on how to integrate Auth Service into your Xamarin.Android app and use the 3rd party auth support for Facebook.
Install the Xamarin environment and project setup.You’ll need to first download and install Visual Studio 2019.
Open Visual Studio and select Mobile development with .NET to install the Xamarin environment.
{
"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"
}
Next make sure you have enabled the Auth Service in AppGallery Connect.
Open Visual Studio, click Create a new project in the start window, select Mobile App (Xamarin.Forms), and set the app name and other required information.
Right-click your project and choose Manage NuGet Packages.
Search for the Huawei.Agconnect.Auth package on the displayed page and install it.
Download the JSON service file from your AppGallery project and add it into the *Assets directory in your project.
Create a new class named HmsLazyInputStreams.cs, and implement the following code to read the JSON file.
Code:
using System;
using System.IO;
using Android.Content;
using Android.Util;
using Huawei.Agconnect.Config;
namespace AppLinking1
{
public class HmsLazyInputStream : LazyInputStream
{
public HmsLazyInputStream(Context context)
: base(context)
{
}
public override Stream Get(Context context)
{
try
{
return context.Assets.Open("agconnect-services.json");
}
catch (Exception e)
{
Log.Error("Hms", $"Failed to get input stream" + e.Message);
return null;
}
}
}
}
Right-click your project and choose Properties. Click Android Manifest on the displayed page and set a package name
Follow the process that Facebook describes to setup your application with their platform. Details can be found here
Finally the last thing we need to do is install the Xamarin Facebook login package.
Right-click your project and choose Manage NuGet Packages. Search for Xamarin.Facebook.Login.Android and install it.
Implement Facebook AuthCreate a login button within your application, this will use the below code to start the login process getting the specific requested account details from Facebook and process this using the call back.
Code:
private void ImgFacebook_Click(object sender, EventArgs e){
callBackManager = CallbackManagerFactory.Create();
ICollection<string> collection = new List<string>();
collection.Add("public_profile");
collection.Add("user_friends");
LoginManager.Instance.LogInWithReadPermissions(this, collection);
LoginManager.Instance.RegisterCallback(callBackManager, new FacebookCallback(this));
}
The Facebook Callback then looks like:
Code:
private class FacebookCallback : Java.Lang.Object, IFacebookCallback {
LoginActivity loginActivity;
public FacebookCallback(LoginActivity loginActivity) {
this.loginActivity = loginActivity;
}
public void OnCancel() {
Log.Debug("IFacebookCallback", "Cancelled.");
}
public void OnError(FacebookException error) {
Log.Error("IFacebookCallback", "Failed: " + error.Message);
}
public void OnSuccess(Java.Lang.Object result) {
LoginResult loginResult = (LoginResult)result;
Log.Debug("IFacebookCallback", "Facebook login successfuly. Access token: " + loginResult.AccessToken.Token);
IAGConnectAuthCredential credential = FacebookAuthProvider.CredentialWithToken(loginResult.AccessToken.Token);
try {
AGConnectAuth connectAuth = AGConnectAuth.Instance;
var signInResult = AGConnectAuth.Instance.SignInAsync(credential);
ISignInResult result = await signInResult;
if (signInResult.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion)){
Log.Debug(TAG, signInResult.Result.ToString());
StartActivity(new Intent(this, typeof(MainActivity)));
Finish();
}
} catch (Exception ex) {
Log.Error(TAG, ex.Message);
Toast.MakeText(this, "SignIn failed: " + ex.Message, ToastLength.Long).Show();
}
}
}
In the OnSuccess method, we have obtained the access token and generated a credential for Facebook Login, and called SignInAsync to pass the credential for sign-in.
Finally, forward OnActivityResult to the callBackManager.
Code:
if (requestCode == 64206){
callBackManager.OnActivityResult(requestCode, (int)resultCode, data);
}
The result code 64206 is defined by Facebook in its Login SDK. It is used to identify the callback for Facebook Login when there are multiple callbacks in OnActivityResult. An interesting fact is that, the hexadecimal value of 64206 is 0xFACE, which is a little trick from Facebook.