More information like this, you can visit HUAWEI Developer Forum
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Huawei Push Kit is a messaging service provided by Huawei for developers. It establishes a communication channel between the cloud and devices. Using HMS Push Kit, developers can send the latest messages to users. This helps developers to maintain closer ties with users and increases user awareness, and activity.
User can tap the message displayed in the notification bar of the device and can open the corresponding app, and view more details.
HMS Push Kit is already available for more than 200+ countries and regions. It offers the capacity of sending 10 million messages per second from the server, delivering 99% of them and providing real time push reports, ultimately helping to improve the DAU of your apps.
In this article we will learn how to send notification using topic-based message sending and how to open a specific page of an app when user taps the notification using Huawei AGC console.
Demo
Prerequisite
1) Must have a Huawei Developer Account.
2) Must have a Huawei phone with HMS 4.0.0.300 or later.
3) Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Things Need To Be Done
1) Create a project in android studio.
2) Get the SHA Key. For getting the SHA key we can refer to this article.
3) Create an app in the Huawei AppGallery connect.
4) Enable push kit setting in Manage APIs section.
5) Provide the SHA Key in App Information Section.
6) Provide storage location.
7) In My Projects tab, navigate to Growing > Push and select service status Enable.
8) After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the Json file in the app folder of the android project.
9) Enter the below maven url inside the repositories of buildscript and allprojects (project build.gradle file):
Code:
maven { url 'http://developer.huawei.com/repo/' }
10) Enter the below plugin in the app build.gradle file:
Code:
apply plugin: 'com.huawei.agconnect'
11) Enter the below HMS Push kit dependencies in the dependencies section:
Code:
implementation 'com.huawei.hms:push:4.0.2.300'
12) Now sync gradle
Topic-based Message Sending
The topic messaging function provided by HUAWEI Push Kit, it allows you to send messages to multiple devices whose users have subscribed to a specific topic. We can write notification messages about the topic as required, and HUAWEI Push Kit sends the messages to correct devices in a reliable manner.
For example, users of a weather forecast app can subscribe to the weather topic and receive notification messages about the best weather for exterminating pests. Users who likes to travel can subscribe to travel information such as travel routes and travel guides.
Note the following items about topic messaging:
1) Topic messaging is best suited for delivering weather or other information that can be obtained publicly.
2) Topic messaging does not limit the number of subscriptions for each topic. However, HMS Push Kit has the following restrictions:
a) An app instance can subscribe to a maximum of 2,000 topics.
b) For Huawei devices running EMUI 10.0 or later, the version of HMS Core (APK) must be 3.0.0 or later. For Huawei devices running an EMUI version earlier than 10.0, the version of HMS Core (APK) must be 4.0.3 or later.
To send messages by topic, we need to complete the following process:
1) User needs to subscribe to a topic via app.
2) After subscribing to a topic, we can send messages to the user based on the topic he/she subscribed.
Subscribed/Unsubscribed to a topic
An app can subscribed/unsubscribed to any existing topics. When an app subscribes to a topic that does not exist, the system creates a topic with the name in HMS Push Kit server. Here we will use HmsMessaging class to subscribe/unsubscribe to a topic.
We will use the subscribe method in the HmsMessaging class to subscribe to a topic. We can add a listener to listen the task execution result to check whether the subscription task is successful. Below is the code to subscribe a topic:
Code:
public void subscribe(String topic) {
try {
HmsMessaging.getInstance(getActivity()).subscribe(topic)
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(Task task) {
if (task.isSuccessful()) {
Log.i("TAG", "subscribe Complete");
Toast.makeText(getActivity(),"subscribe Complete",Toast.LENGTH_LONG).show();
} else {
Log.e("TAG", "subscribe failed: ret=" + task.getException().getMessage());
Toast.makeText(getActivity(),"subscribe failed: ret=" + task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
Log.e("TAG", "subscribe failed: exception=" + e.getMessage());
Toast.makeText(getActivity(),"subscribe failed: ret=" + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
We will use the unsubscribe method in the HmsMessaging class to unsubscribe a topic.
Code:
public void unsubscribe(String topic) {
try {
HmsMessaging.getInstance(getActivity()).unsubscribe(topic)
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(Task task) {
if (task.isSuccessful()) {
Log.i("TAG", "unsubscribe Complete");
Toast.makeText(getActivity(),"unsubscribe Complete",Toast.LENGTH_LONG).show();
} else {
Log.e("TAG", "unsubscribe failed: ret=" + task.getException().getMessage());
Toast.makeText(getActivity(),"unsubscribe failed: ret=" + task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
Log.e("TAG", "unsubscribe failed: exception=" + e.getMessage());
Toast.makeText(getActivity(),"unsubscribe failed: exception=" + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
Sending notification based on the topic using console
The beauty of topic based subscription is we don’t need to add any push token to send notification. We only need to provide the topic in order to send notification and the notification will be served to the devices which subscribed to that particular topic.
Note: In order to make it work, we need to subscribe to a topic in the app as shown below:
Here we subscribed to sports as topic. Let us see how we can send notification using topic-based subscription.
Steps required in order to send notification based on topic using AGC console:
1) In My Projects tab, navigate Growing > Push Kit and select service status Enable.
2) After enabling the service, click Add Notification button.
3) Under content provide mandatory details like Name, Type, Display, Header, Title and Body. Select Open app in Action and Homepage in App page drop-downs, as shown below:
This is not all. For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202326236067510002&fid=0101187876626530001
Related
More information like this, you can visit HUAWEI Developer Forum
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202333898987840045&fid=0101187876626530001
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Huawei Awareness Kit provides our application to obtain information such as current time, location, behavior, audio device status, ambient light, weather, and nearby beacons. Using this information we can get an advantage over user's current situation more efficiently and can manipulate data for better user experience.
In this article, we will use weather information using HMS Awareness Kit for manipulating warm up exercise for user.
Demo
In the above demo, the warm up exercise for user will get change according to the weather condition. Here the weather condition is divided into two parts:
1) Outdoor warm up exercise: When the weather condition is normal such as sunny or not raining, then the warm up exercise will get change to running.
2) Inside warm up exercise: When the weather condition is abnormal such as raining or snow fall, then the warm up exercise will get change to invisible jumping rope, burpee and squats.
By this way we are providing user a better experience without avoiding any exercise due to certain condition. It’s a win-win situation for developers to not to lose any user due to bad user experience.
Prerequisite
1) Must have a Huawei Developer Account.
2) Must have a Huawei phone with HMS 4.0.0.300 or later.
3) Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Things Need To Be Done
1) Create a project in android studio.
2) Get the SHA Key. For getting the SHA key we can refer to this article.
3) Create an app in the Huawei AppGallery connect.
4) Enable awareness kit setting in Manage APIs section.
5) Provide the SHA Key in App Information Section.
6) Provide storage location.
7) After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the Json file in the app folder of the android project.
8) Enter the below maven url inside the repositories of buildscript and allprojects (project build.gradle file):
Code:
maven { url ‘http://developer.huawei.com/repo/’ }
9) Enter the below plugin in the app build.gradle file:
Code:
apply plugin: ‘com.huawei.agconnect’
10) Enter the below HMS Push kit dependencies in the dependencies section:
Code:
implementation ‘com.huawei.hms:awareness:1.0.6.301’
11) Enter the below permission in android manifest file
Code:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
12) Now Sync the gradle.
Weather Awareness
It is used for providing weather information such as current day or next seven days weather information of a specific device location. It does not support barrier information or function.
Code:
public void sendWeatherId(){
Awareness.getCaptureClient(this).getWeatherByDevice()
.addOnSuccessListener(new OnSuccessListener<WeatherStatusResponse>() {
@Override
public void onSuccess(WeatherStatusResponse weatherStatusResponse) {
WeatherStatus weatherStatus = weatherStatusResponse.getWeatherStatus();
List<HourlyWeather> hourlyWeather = weatherStatus.getHourlyWeather();
Utility.setWeatherId(getApplicationContext(),hourlyWeather.get(1).getWeatherId());
if(Utility.getWeatherId(getApplicationContext())!=0){
goToValidPage();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e("TAG", "get Hourly weather failed");
}
});
}
The above code is used to get the weather information such as sunny, rain, cloudy etc. Using this information we will manipulate the warm up exercise and show user the list of exercise.
getWeatherByDevice
This method is used to obtain the weather information using the current location of a device. There are some restriction using this method:
1) The total number of capture API calls every 5 seconds cannot exceed 20
2) The total number of capture API calls every hour cannot exceed 1000
3) This function is available only on device with API level 24 or later
4) ACCESS_FINE_LOCATION permission is needed in android manifest file.
WeatherStatus
This is the main API where we will fetch the weather id. Using this id we will manipulate the exercise. This API contain five methods:
1) getAqi()
2) getWeatherSituation()
3) getDailyWeather()
4) getHourlyWeather()
5) getLiveInfo()
Here we will use getHourlyWeather to obtain weather information in the next 24 hours. The information will fetch weather ID, time, temperature and rainfall probability.
Opening YouTube Video in HMS devices
Code:
public static void watchYoutubeVideo(Context context, String id){
try {
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + id));
context.startActivity(webIntent);
} catch (ActivityNotFoundException ex) {
}
}
The Id here is YouTube Id.
CountDownTime
As the name implies to counts down the time specified in milliseconds.
Code:
mCountDownTimer = new CountDownTimer(TIMER_DURATION, TIMER_INTERVAL) {
@Override
public void onTick(long millisUntilFinished) {
txtTimer.setText("00:"+(millisUntilFinished / 1000 < 10 ? "0"+ millisUntilFinished / 1000 : String.valueOf(millisUntilFinished / 1000)));
mTimeRemaining = millisUntilFinished; // Saving timeRemaining in Activity for pause/resume of CountDownTimer.
}
@Override
public void onFinish() {
mCountDownTimer.cancel();
Intent intent = new Intent(ReadyActivity.this, CurrentWorkoutActivity.class);
startActivity(intent);
finish();
}
}.start();
Timer
In case user go for run we need to have a timer to capture the duration of its completion.
Code:
private void timer (){
Timer timer = new Timer();
countTimer = 0;
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
String s_time = String.format("%02d:%02d:%02d",
countTimer / 3600,
(countTimer % 3600) / 60,
countTimer % 60);
System.out.println("TIMER >>>" + s_time);
txtTimer.setText(s_time);
if (!pauseTimer) countTimer++;
}
});
}
}, 1000, 1000);
}
What we learn?
We learn how to manipulate data using HMS Weather Awareness Kit and also situation where we need the most.
GitHub
Very soon I am going to post the entire code on GitHub. So come back again to check it out.
For more reference
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/service-introduction-0000001050031140-V5
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/weather-awareness-0000001050121038-V5
In 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.
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
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
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