Huawei AppGallery Connect’s App Messaging service allows you to send targeted, useful in-app messages to your users.
The look and content of messages are completely customisable, and there is a wide range of triggers and filters that can be used to decide who will receive a message and when.
Let's take a look today at how we can set this up to work within a flutter project.
As always we will start with a fresh project but of course, you can just as easily use this guide to build the service into an app you already have!
Installing the Flutter Environment
Download the Flutter SDK.
Decompress the package to any directory.
Add the Flutter command file to the environment variable.
Download the Flutter and Dart plugins in Android Studio.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Enabling the Service and Creating a Flutter projectSign in to AppGallery Connect, click My projects, click your project, go to Grow > App Messaging, and click Use now. For more information, please refer to App Messaging.
If you do not have an Android project, create one first.
After completing these steps, you can start creating an in-app message.
Click New in the upper right corner.
Set Name and Description
Set the style and content and click Next.
Select a message type from the Layout drop-down list, and set its style and content. Currently, the Modal, Image, and Banner message types are supported.
Set target users and click Next.
In App, select the name of the app package for which you need to publish the in-app message.
You can click New condition to add a condition for matching target users, which include app version, OS version, language, country/region, audience, and more. Among the types, User attributes are defined under HUAWEI Analytics > Management > User attributes, and Prediction is defined by creating prediction tasks under My projects > Grow > Prediction.
Set the message sending time
Message display is triggered by specific events. App Messaging supports two types of trigger events: preset events and HUAWEI Analytics events.
(Optional) Set conversion events. Before setting a conversion event, you need to toggle it on first, which can be done as follows:
Go to HUAWEI Analytics > Management > Events and toggle Mark as conversion event and Event switch on for the specified event. In addition to the events the SDK collects, you can also create a preset or custom event for event tracking and analysis.
Finally, Click Save or Publish.
Integrating the Service SDKAdd dependenciesStart by creating a Flutter project in Android Studio (or opening one).
Then add the agconnect-services.json file from your AppGallery project to the android/app directory
Within the project level build.gradle file make sure to include the huawei maven repo and add the agcp package as a dependency.
Code:
buildscript {
repositories {
google()
mavenCentral()
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.4'
classpath 'com.huawei.agconnect:agcp:1.6.2.300'
}
}
Next in your app level build.gradle apply the agconnect plugin as so:
Code:
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.huawei.agconnect'
Then in your pubspec.yaml file add the App Messaging SDK dependency.
Code:
dependencies:
flutter:
sdk: flutter
agconnect_appmessaging: ^1.2.0+300
Displaying an In-App MessageIf you choose to display a message using the default message layout, the development process is totally coding-free.
By integrating the SDK as above you are all good to go, your creating message will be displayed as per its filters and triggers.
You can also call APIs provided by the service SDK to customize your in-app message.
Customising the Message LayoutAdd the following code to onCreate in MainActivity,
Code:
AGCAppMessagingCustomEventStreamHandler.addCustomView();
so that the service SDK can listen to the corresponding event and apply the customized layout.
Code:
streamSubscriptionDisplay = agconnectAppmessaging.customEvent.listen((event) {
showDialog(context ,event.toString());
agconnectAppmessaging.handleCustomViewMessageEvent
(AppMessagingEventType.onMessageDismiss(AppMessagingDismissTypeConstants.CLICK));
});
Then the message is displayed in your app.
Code:
void _showDialog(BuildContext context, String content) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
key: Key("dialog"),
title: Text("Result"),
content: Text(content),
actions: <Widget>[
FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
}
Testing an In-App MessageApp Messaging allows you to test an in-app message before it is published. You need to obtain the Anonymous Application Identifier (AAID) of your test device by adding the following code to your Android app module.
Code:
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
textView.setText(aaid);
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
Sign in to AppGallery Connect, go to Grow > App Messaging > Messages, find the message that you created, click and select Test in the Operation column.
Click Add test user and enter the AAID
Click Save. Check whether the test message is properly displayed on your test device
Related
More information like this, you can visit HUAWEI Developer Forum
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201346110142010150&fid=0101187876626530001
HUAWEI Account Kit offers very simple, quick and secure sign in and authorization functionalities which help developers to implement hassle free and quick sign in functionalities for applications.
HUAWEI Account Kit offers services on different parameters as
Quick and Standard
Massive user base and global services
Secure, reliable, and compliant with international standards
Quick sign-in to apps
Development Overview
Prerequisite
1. Must have a Huawei Developer Account
2. Must have a Huawei phone with HMS 4.0.0.300 or later
3. React Native environment with Android Studio, Node Js and Visual Studio code.
Major Dependencies
1. React Native CLI : 2.0.1
2. Gradle Version: 6.0.1
3. Gradle Plugin Version: 3.5.2
4. React Native Account Kit SDK : 5.0.0.300
5. React-native-hms-account kit gradle dependency
6. AGCP gradle dependency
Preparation
1. Create an app or project in the Huawei app gallery connect, click My apps, as shown 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"
}
1.0 Click on New app.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.
2.0 Add the below information to create a new app and project
2.1 Once app is created, navigate to My projects
2.2 Click on the created project, as shown below.
2.3 Enable the AccountKit API
2.4 Put SHA signature generated using Android Studio
2.5 Download agconnect-services.json services file and paste it under App folder of the project.
3. Create a react native project, use the below command
Code:
“react-native init project name”
4. Download the React Native Account Kit SDK and paste it under Node Modules directory of React Native project.
Tips
1. Run below command under project directory using CLI if you cannot find node modules.
Code:
“npm install” & “npm link”
Integration
1. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
2. Configure app level build.gradle. (Add to dependencies)
Code:
Implementation project (“:react-native-hms-account”)
3. Linking the HMS Account Kit Sdk.
Run below command in the project directory
Code:
react-native link react-native-hms-account
Adding permissions
Add below permissions to Android.manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Development Process
Once sdk is integrated and ready to use, add following code to your App.js file which will import the API’s present.
Import the SDK
Silent Sign In
On Cancel Authorization
On Adding Authorization Scopes
Retrieve SMS Verification Code
Testing
Import the SDK
Add below line of code in the app.js file
Code:
import RNHMSAccount from "react-native-hms-account";
Silent Sign In
With silent sign in, the users can sign in without using their login credientials for consecutive sign-ins. To silent sign in, invoke the silentSignIn method of the HMSAccount module. The promise is resolved if the silent sign in is successful, is rejected otherwise.
Add below code on the “SILENT SIGN IN” button click
Code:
const onSilentSignIn = () => {
RNHMSAccount.HmsAccount.silentSignIn()
.then((response) => {
logger(JSON.stringify(response));
})
.catch((err) => {
logger(err);
});
};
On Cancel Authorization
Cancelling authorization is intended to increase security by forcing the users to use login credentials while signing in. To cancel authorization, invoke the cancel Authorization method of the HMSAccount module. The promise is resolved if the silent sign in is successful, is rejected otherwise.
Add below code on the “ONCANCELAUTHORIZATION” button click.
Code:
const onCancelAuthorization = () => {
RNHMSAccount.HmsAccount.cancelAuthorization()
.then((response) => {
logger(JSON.stringify(response));
})
.catch((err) => {
logger(err);
});
};
On Adding Authorization Scopes
Auth Manager class is responsible for creating the authorization scopes to build the data.
Add below code on the “ONADDAUTHSCOPES” button click.
Code:
const onAddAuthScopes = () => {
let buildData = {
requestCode: 888,
scopes: [RNHMSAccount.HmsAccount.SCOPE_ID_TOKEN],
};
RNHMSAccount.HuaweiIdAuthManager.addAuthScopes(buildData)
.then((response) => {
logger(JSON.stringify(response));
})
.catch((err) => {
logger(err);
});
};
Retrieve SMS Verification Code
Read SMS manager is a service to listen verification code SMS events. To start read SMS manager, invoke the startReadSMSManager method of the module.
Code:
const onStartReadSMSManager = () => {
RNHMSAccount.SMSManager.startReadSMSManager()
.then((response) => {
logger(JSON.stringify(response));
})
.catch((err) => {
logger(err);
});
};
Testing
Run the below command to build the project
Code:
React-native run-android.
After successful build, run the below command in the android directory of the project to create the signed apk.
Code:
gradlew assembleRelease
Results
References
https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/introduction-0000001050725712
Conclusion
Adding Account kit functions seem easy.
In this article, we’ll be looking at some of the APIs that Account Kit provides and learn how to use them in our Flutter projects.
Huawei Account Kit
Account Kit provides a simple and quick authorization experience to users. It enables to save time from long authorization periods and it’s two factor authentication process keeps users information safe. Account Kit allows you to connect to the Huawei ecosystem using your Huawei Id from a range of devices, such as mobile phones and tablets. Users can quickly and conveniently sign in to apps with their Huawei Ids after granting an initial access permission.
Configuring the project
Registering as a Developer
As first, you need to create a Huawei developer account and complete the identity verification. For details, please refer to Registering a Huawei Id.
Creating an APP
Sign in AppGallery Connect and create a new project.
Add a new app to your project by clicking the Add App 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"
}
Generating a Signing Certificate Fingerprinter
Signing certificate fingerprints are used to verify the authenticity of an App when it attempts to access an HMS Core service through the HMS Core SDK. So before using the HMS Core service, you must generate a signing certificate fingerprint and configure it in AppGallery Connect.
Generate a Signing Certificate by referring here.
Then you’ll need to export the SHA256 Fingerprint by using keytool provided by JDK. You can find detailed steps here.
Adding Fingerprint Certificate to AppGallery Connect
On the application information page of the project, click to add your SHA256 fingerprint. Then click ✓ to save fingerprint.
Enabling Account Kit Service
On the application information page, click Manage APIs and make sure Account Kit is enabled.
Integrating HMS and Account Plugin to Flutter Project
Open pubspec.yaml file of your project and add Huawei Account Plugin as a dependency.
Code:
dependencies:
flutter:
sdk: flutter
huawei_account: ^5.0.0+300
Download agconnect-services.json file from application information page.
Move the file to the android/app directory with the signing certificate file you’ve created.
Open the android/build.gradle file and configure the Maven repository address and agconnect plugin for the HMS Core SDK.
Code:
buildscript {
repositories {
// Other repositories
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
// Other dependencies
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
}
}
allprojects {
repositories {
// Other repositories
maven { url 'https://developer.huawei.com/repo/' }
}
}
Add the AppGallery Connect plugin to your app level build.gradle file.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
Then add the signing configurations in the same file. Don’t forget that your applicationId must be same as the one you created in AppGallery Connect. Also change your minSdkVersion to 19.
Code:
android {
defaultConfig {
applicationId "<application_id>"
minSdkVersion 19
targetSdkVersion 29
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
signingConfigs {
config {
storeFile file('<keystore_file>')
storePassword '<keystore_password>'
keyAlias '<key_alias>'
keyPassword '<key_password>'
}
}
buildTypes {
debug {
signingConfig signingConfigs.config
}
release {
signingConfig signingConfigs.config
}
}
}
Now we’re done with the integration part and ready to use the Account Plugin in our application.
Using Huawei Account Kit Flutter Plugin
Setting Up The Authorization
Account Plugin allows you to customize the authorization. You can request users to authorize their email addresses, profile information or access tokens. To accomplish that, you can use AuthParamHelper class.
Create an instance of AuthParamHelper class. Then set the parameters you want to customize.
Code:
AuthParamHelper helper = new AuthParamHelper();
// You can set many options by using cascades
helper..setEmail()..setRequestCode(8888);
Signing In
Now we’re going to call signIn method through HmsAccount class and pass our helper instance to it. In return, this method gives us the Huawei Id information through AuthHuaweiId class.
Code:
try {
// Make sure you handle the possible exceptions.
final AuthHuaweiId authHuaweiId = await HmsAccount.signIn(helper);
} on Exception catch (e) {
print(e.toString());
}
As this method is triggered, an authorization screen shows up. After clicking the login button, you can see the Huawei Id information is received.
Account Plugin has signOut method which clears the user’s Huawei Id information when it comes to sign out from an app. But the information is not permanently deleted.
Code:
try {
// Make sure you handle possible exceptions.
final bool result = await HmsAccount.signOut();
} on Exception catch (e) {
print(e.toString());
}
Revoking Authorization
After signing in for the first time, when users try to sign in again, the authorization screen will not show up unless users revoke it. Huawei Id information will be received directly. Once the authorization is revoked, logged id information will be deleted. And the authorization screen will be shown on another login attempt.
Code:
try {
// Make sure you handle possible exceptions.
final bool result = await HmsAccount.revokeAuthorization();
} on Exception catch (e) {
print(e.toString());
}
Sms Verification
One of the options that Account Plugin provides us is the sms verification. This service can catch sms messages in certain formats. Unlike the other authorization methods, you should be able to send sms messages for this special service.
Obtaining Application’s Hash Code
To catch upcoming sms messages, we need to know the hash code value which is unique in each app. Account Plugin provides obtainHashcode method to get that.
Code:
try {
// Make sure you handle possible exceptions.
final String hashcode = await HmsAccount.obtainHashCode();
} on Exception catch (e) {
print(e.toString());
}
Sending Sms Messages
The messages you’ll send should be as follows:
Code:
prefix_flag short message verification code is ****** hash_code
prefix_flag indicates the prefix of an SMS message, which can be <#>, [#], or \u200b\u200b. \u200b\u200b are invisible Unicode characters.
short message verification code is indicates the content of an SMS message, which is user-defined.
****** indicates the verification code.
Receiving Sms Messages
Account Plugin comes with smsVerification method to listen and catch the right formatted messages. Once it is called, the app starts listening. Waits for the messages for five minutes before timing out. Returns the message or error code depending on the situation.
Code:
HmsAccount.smsVerification(({errorCode, message}){
if (message != null) {
// Use the message
} else {
print("Error: $errorCode");
}
});
It’s all done. Now you’re ready to use Account Plugin in your Flutter applications.
Conclusion
Huawei Account Kit is such an easy and secure way to carry out authorization processes, along many other kits with powerful solutions. I think these services will keep providing a nice experience for both developers and users as they get bigger and better.
You can check some other articles about Hms Core Plugins below, and feel free to ask any question about this article in the comments.
Introduction
In this article, we will learn how to implement Huawei Awareness kit features, so we can easily integrate these features in to our Flutter application. In this article we are going to take a look at the Awareness kit Capture API features such as Dark mode awareness and App status awareness.
{
"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"
}
What is Huawei Awareness kit Service?
Huawei Awareness kit supports to get the app insight into a users’ current situation more efficiently, making it possible to deliver a smarter, more considerate user experience and it provides the users’ current time, location, behavior, audio device status, ambient light, weather, and nearby beacons, application status, and mobile theme mode.
Restrictions
1. Dark mode: It supports EMUI 10.0 or later for Huawei devices and non-Huawei devices required Android 10.0 or later (API level 29 is required).
2. App status: It supports EMUI 5.0 or later for Huawei devices and non-Huawei devices currently it is not supporting
Requirements
1. Any operating system(i.e. MacOS, Linux and Windows)
2. Any IDE with Flutter SDK installed (i.e. IntelliJ, Android Studio and VsCode etc.)
3. Minimum API Level 29 is required.
4. Required EMUI 10.0 For Dark-mode and EMUI 5.0 for App status.
How to integrate HMS Dependencies.
1. First of all, we need to create an app on AppGallery Connect and add related details about HMS Core to our project. For more information check this link
2. Enable the Awareness Kit in the Manage API section and add the plugin.
3. Add the required dependencies to the build.gradle file under root folder.
Code:
maven {url 'http://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
4. Now we can implement Awareness Kit plugin. To implement Awareness Kit to our app, we need to download the plugin. Follow the URL for cross-platform plugins.
5. After completing all the above steps, you need to add the required kits’ Flutter plugins as dependencies to pubspec.yaml file. You can find all the plugins in pub.dev with the latest versions.
Code:
huawei_awareness:
path: ../huawei_awareness/
After adding them, run flutter pub get command. Now all the plugins are ready to use.
Note: Set multiDexEnabled to true in the android/app directory, so the app will not crash.
Use Awareness to get the dark mode status
With Dark-mode Status Awareness, we can detect the dark mode status of the device. We can get the status using capture API.
Code:
void loadAppTheme() async {
DarkModeResponse response = await AwarenessCaptureClient.getDarkModeStatus();
bool isDarkMode = response.isDarkModeOn;
setState(() {
if (isDarkMode) {
Provider.of<ThemeChanger>(context).setTheme(darkTheme);
} else {
Provider.of<ThemeChanger>(context).setTheme(lightTheme);
}
});
}
Use Awareness to get the Application status
With Application status Awareness, we can detect whether application is in which mode like silent, running using package name.
Code:
void checkAppStatus() async {
String packName = "******************";
ApplicationResponse response =
await AwarenessCaptureClient.getApplicationStatus(
packageName: packName);
int appState = response.applicationStatus;
setState(() {
switch (appState) {
case ApplicationStatus.Unknown:
_showDialog(context, "Demo Application Not found");
print("log1" + "Application Not found");
break;
case ApplicationStatus.Silent:
_showDialog(context, "Demo Application Currently in silent mode");
print("log1" + "Application silent");
break;
case ApplicationStatus.Running:
_showDialog(context, "Demo Application Currently in Running mode");
print("log1" + "Application Running");
break;
}
});
}
Final code here
Code:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<ThemeChanger>(
create: (context) => ThemeChanger(ThemeData.light()),
child: new App(),
);
}
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appState = Provider.of<ThemeChanger>(context);
return MaterialApp(
title: "WellFit",
theme: appState.getTheme(),
home: Scaffold(
body: Tabs(),
),
);
}
}
ThemeNotifier class
Code:
class ThemeChanger with ChangeNotifier {
ThemeData _themeData;
ThemeChanger(this._themeData);
getTheme() => _themeData;
setTheme(ThemeData themeData) {
_themeData = themeData;
notifyListeners();
}
}
Demo
Tips and Tricks
1. Download latest HMS Flutter plugin.
2. Set minSDK version to 29 or later.
3. Do not forget to click pug get after adding dependencies.
4. Do not forget to set data processing location.
5. Refer this URL for supported Devices list.
Conclusion
In this article, I have covered two services Dark-mode awareness and App status Awareness.
Using Dark-mode awareness we can easily identify which theme currently we activated in settings page.
Using App Status awareness we can monitor the application in which state like silent or running these two we covered in this article.
Thanks for reading! If you enjoyed this story, please click the Like button and Follow. Feel free to leave a Comment below.
Reference
Awareness Kit URL
Original Source
With the release of AppGallery Connect version 1.5.2 the Auth service now has full support for making use of unified sign-in with a Facebook account!
This new functionality makes AppGallery Connect Auth a great option for all of your app’s authentication needs both on Huawei devices and other Android devices.
So how do we go about using unified sign-in with a Facebook account? Let’s take a look!
Configuring the Facebook Login EnvironmentFirst, you’ll need to configure the Facebook Login environment.
Select or create a Facebook 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"
}
Edit your resource file. Copy the following code to the /app/res/values/strings.xml file of your Android project.
Edit your manifest file. Add the following uses-permission element following the application element in the /app/manifest/AndroidManifest.xml file of your Android project.
Copy the following meta-data element to the application element.
Associate your package name and default activity class with your app and click Save. Confirm the use of this package name (skip this if your app has not been released on Google Play).
Develop a key hash using the following command, and release it for your app.
If you haven’t installed OpenSSL (openssl-for-windows) for your project, please go to Google Code Archive and download it as required.
keytool -exportcert -alias authdemounion -keystore F:\1.test\4.Auth\AuthDemo-Union\app\authdemounion.jks | openssl sha1 -binary | openssl base64
The command format is as follows:
keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH* | openssl sha1 -binary | openssl base64
The Facebook Login environment has now been successfully configured. Let’s move on to the operations relevant to Auth Service.
Enabling Auth ServiceSign in to AppGallery Connect, create a project and an app, and enable Auth Service. You’ll need to enter the App ID and App Secret for your app when enabling Facebook under Authentication modes, which can be found under Settings > Basic on Facebook for Developers. If they are not displayed, click the button following App Secret to show them.
Generating the Certificate Fingerprint for Your Android ProjectIf the demo project does not provide a Java KeyStore, go to Generate Signed Bundle or APK and click Create new.key store to create one
Generate an SHA-256 certificate fingerprint. Run the following command and enter the configured password to generate a SHA-256 certificate fingerprint.
keytool -list -v -keystore you_path\AuthDemo-Union\app\authdemounion.jks
Open the app-level build.gradle file, and configure the certificate information for your project
Click here to view the sample code.
Configure the generated SHA-256 certificate fingerprint in AppGallery Connect. (If you do not perform this step, error 6003 will be reported.)
Configure Your AppOpen the project-level build.gradle file and configure information, including the Maven repository address. The code is as follows:
Code:
buildscript {
repositories {
google()
jcenter()
maven { url 'http://developer.huawei.com/repo/' } // Configure this maven.
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.1"
classpath 'com.huawei.agconnect:agcp:1.5.1.300' // Configure this path.
// NOTE: Do not copy your dependencies in here, which should be included
// in the build.gradle files of each module.
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'http://developer.huawei.com/repo/' } // Configure this maven.
}
}
Open the app-level build.gradle file and configure information, including the SDK information and app plug-in address. The code is as follows:
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect' // Configure the apply plug-in.
android {…}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation "com.huawei.agconnect:agconnect-auth-facebook:1.5.2.201" // Configure this SDK.
implementation 'com.huawei.agconnect:agconnect-auth:1.5.2.201' // Configure this SDK.
}
Add the code for implementing unified sign-in:
Java:
private void FaceBookLogin(){
Log.i("AuthDemo", "start:" );
AGConnectAuth.getInstance().signIn(this, AGConnectAuthCredential.Facebook_Provider)
.addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
// onSuccess
AGConnectUser user = signInResult.getUser();
Log.i("AuthDemo", "success:" + user);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// onFail
Log.i("AuthDemo", "failed:" + e.getMessage());
}
});
}
// Activity lifecycle required by the unified sign-in.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
AGConnectApi.getInstance().activityLifecycle().onActivityResult(requestCode, resultCode, data);
Viewing the Result and LogsOnce you run your signed APK on an Android phone and call the FaceBookLogin method, you’ll get the following page.
You can tap CONTINUE AS LINKING and sign in to your app with your Facebook account. The following log information will be displayed.
Compared with the traditional implementation mode, the unified sign-in has greatly simplified the development process. It is strongly recommended that you use the new mode.
For details about Auth Service, please refer to:
Auth Service document for Android
Guide for integrating Facebook account
Thanks for sharing.
Huawei AppGallery Connect’s App Messaging service allows you to send targeted, useful in app messages to your users.
The look and content of messages are completely customisable, and there is a wide range of triggers and filters that can be used to decide who will receive a message and when.
Lets take a look today at how we can set this up to work within an Android project.
As always we will start with a fresh project but of course you can just as easily use this guide to build the service into an app you already have!
Enabling the ServiceSign in to AppGallery Connect, click My projects, click your project, go to Grow > App Messaging, and click Use now. For more information, please refer to App Messaging.
If you do not have an Android project, create one first.
After completing these steps, you can start creating an in-app message.
Click New in the upper right corner.
{
"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"
}
Set Name and Description
Set the style and content and click Next.
Select a message type from the Layout drop-down list, and set its style and content. Currently, the Modal, Image, and Banner message types are supported.
Set target users and click Next.
In App, select the name of the app package for which you need to publish the in-app message.
You can click New condition to add a condition for matching target users, which include app version, OS version, language, country/region, audience, and more. Among the types, User attributes are defined under HUAWEI Analytics > Management > User attributes, and Prediction is defined by creating prediction tasks under My projects > Grow > Prediction.
Set the message sending time
Message display is triggered by specific events. App Messaging supports two types of trigger events: preset events and HUAWEI Analytics events.
(Optional) Set conversion events. Before setting a conversion event, you need to toggle it on first, which can be done as follows:
Go to HUAWEI Analytics > Management > Events and toggle Mark as conversion event and Event switch on for the specified event. In addition to the events the SDK collects, you can also create a preset or custom event for event tracking and analysis.
Finally, Click Save or Publish.
Integrating the Service SDKAdd Maven repository configuration to the build.gradle file of your project.
Code:
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath 'com.huawei.agconnect:agcp:1.5.2.300'
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Open the app-level build.gradle file and configure the App Messaging SDK
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
android {…..}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.5.2.300'
}
In AppGallery Connect, click My projects, and find your project from the list. Go to Project settings > General information, download the agconnect-services.json file, and save the file to the app directory of your Android project.
Displaying an In-App MessageIf you choose to display a message using the default message layout, the development process is totally coding-free.
By integrating the SDK as above you are all good to go, your creating message will be displayed as per its filters and triggers.
You can also call APIs provided by the service SDK to customize your in-app message.
Customising the Message LayoutFirst, you need to customize a message display class. To do so, implement AGConnectAppMessagingDisplay and override the displayMessage method.
Code:
public class CustomDisplayView implements AGConnectAppMessagingDisplay {
@Override
public void displayMessage(@NonNull AppMessage appMessage,
@NonNull AGConnectAppMessagingCallback callback) {
}
}
Define an AlertDialog in displayMessage and copy the layout file to the code. The sample code is as follows:
Code:
@Override
public void displayMessage(@NonNull AppMessage appMessage, @NonNull AGConnectAppMessagingCallback callback) {
Log.d(TAG, appMessage.getId() + "");
showDialog(appMessage, callback);
}
private void showDialog(@NonNull final AppMessage appMessage, @NonNull final AGConnectAppMessagingCallback callback) {
View view = LayoutInflater.from(activity).inflate(R.layout.custom_view, null, false);
final AlertDialog dialog = new AlertDialog.Builder(activity).setView(view).create();
Button click = view.findViewById(R.id.click);
Button dismiss = view.findViewById(R.id.dismiss);
TextView id = view.findViewById(R.id.id);
id.setText("MessageID: " + appMessage.getId());
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// set button callback
callback.onMessageClick(appMessage);
callback.onMessageDismiss(appMessage, AGConnectAppMessagingCallback.DismissType.CLICK);
dialog.dismiss();
}
});
dismiss.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//set button callback
callback.onMessageDismiss(appMessage, AGConnectAppMessagingCallback.DismissType.CLICK);
dialog.dismiss();
}
});
dialog.show();
dialog.getWindow().setLayout((getScreenWidth(activity) / 4 * 3), LinearLayout.LayoutParams.WRAP_CONTENT);
callback.onMessageDisplay(appMessage);
}
Call addCustomView to implement the custom layout.
Code:
CustomView customView = new CustomView(MainActivity.this);
appMessaging.addCustomView(customView);
Test in app messageObtain the Anonymous Application Identifier (AAID) of your test device, which is used to identify app instances running on mobile devices during app installation. Compared with device-level hardware IDs that cannot be reset, the privacy of AAID is much higher. We can obtain the AAID through coding.
Code:
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
textView.setText(aaid);
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
Sign in to AppGallery Connect, go to Grow > App Messaging > Messages, find the message that you need to test, and click Test in the Operation column.
Click Add test user and enter the AAID in the test box.
Click Save. Check whether the test message can be properly displayed and operated.
For details, please refer to the development guide of App Messaging.