View attachment 5208391
In this article, you guys can read how I had conversation with my girlfriend about Account kit integration in the Flutter.
Rita: Hey, Happy morning.
Me: Happy morning.
Rita: I heard that Huawei supports Account kit in flutter. Does it really support? Do you have any idea about it?
Me: Yes it supports. I’ve idea about account kit in flutter.
Rita: That’s great, can you explain me?
Me: Why not definitely.
Me: But what exactly you want to know about account kit in flutter?
Rita: I have couple of question check below questions.
1. What is account kit?
2. What is the benefit of account kit?
3. How much time it takes to integrate in flutter?
4. How to integrate Huawei account kit in flutter?
Me: OMG so many questions. I should rename your name to Question bank instead of your name. But fine I’ll answer all your questions. Let me answer one by one.
Rita: Okay.
Me: Here is your answer for first question.
What is account kit?
To answer this question let me give introduction about account kit.
Introduction
Huawei Account Kit is a development kit and account service developed by Huawei. Easy to integrate Sign In-based functions into your applications. It save user’s long authorization period and also two factor authorization user information is very safe. Flutter account kit plugin allows users to connect with Huawei Ecosystem using Huawei IDs. It supports both mobiles and tablets. User can sign any application from Huawei account.
Rita: Awesome introduction (@Reader its self-compliment. If you have any questions/compliments/comments about account kit in flutter. I’m expecting it in comments section.)
Me: I hope now you got answer for what is account kit?
Rita: Yes, I got it.
Me: Let’s move to next question
What is the benefit of account kit?
Me: Before answering this question, let me ask you one question. How do you sign up for application?
Rita: Traditional way.
Me: Traditional way means?
Rita: I’ll ask user information in the application.
Me: Okay, let me explain you one scenario, if you are referring same thing let me know.
Rita: Fine
Me: Being a developer, what we usually do is we collect user information in sign up screen manually. User first name, last name, email id, mobile number, profile picture etc. These are the basic information required to create account. Let me share you one screen.
{
"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"
}
Me: This is how you ask for sign up right?
Rita: Exactly you are right, I’m referring same things.
Me: See in this traditional way user has to enter everything manually it is very time consuming. You know nowadays users are very specific about time. User needs everything in one click for that, being a developer we need to fulfill user requirement. So Huawei built a Flutter plugin for account kit to overcome the above situation.
Me: Now you got the problem right?
Rita: Yes.
Me: So, to avoid above situation you can sign up using Huawei account kit and get user information in one click more over user information is safe.
Me: I hope I have answered your question what is the benefit of account kit?
Rita: Yes
Me: Now let me explain about features of Account Kit.
Features of Account kit
1. Sign in
2. Silent sign in
3. Sign out
4. Revoke authorization.
Me: Now let’s move to next question.
How much time it takes to integrate in flutter?
Me: this is very simple question it hardly takes 10 minutes.
Rita: Oh is it? It means Integration will be very easy.
Me: Yes, you are clever.
Rita: ha ha ha. I’m not clever Huawei made it very easy, I just guessed it.
Me: Okay, are you getting bored?
Rita: No, why?
Me: If you are bored, I just wanted to crack a joke.
Rita: Joke? That’s too from you? No buddy because I’ll get confuse where to laugh and you know sometimes I don’t even get you have finished your joke.
Me: Everybody says the same thing.
Rita: Then imagine, how bad you in joke.
Me: Okay Okay, lets come back to concept (In angry).
Rita: Don’t get angry man I’m in mood of learning not in mood of listening joke.
Me: Okay, let’s move to next question.
How to integrate Huawei account kit in flutter?
To answer your question follow the steps.
Step 1: Register as a Huawei Developer. If you have already a Huawei developer account ignore this step.
Step 2: Create a Flutter application in android studio or any other IDE.
Step 3: Generate Signing certificate fingerprint.
Step 4: Download Account Kit Flutter package and decompress it.
Step 5: Add dependencies pubspec.yaml. Change path according to your downloaded path.
Step 6: After adding the dependencies, click on Pub get.
Step 7: Navigate to any of the *.dart file and click on Get dependencies.
Step 8: Sign in to AppGallery Connect and select My projects.
Step 9: Click your project from the project list.
Step 10: Navigate to Project Setting > General information and click Add app.
Step 11: Navigate to Manage API and Enable Account kit.
Step 12: Download agconnect-services.json and paste in android/app folder.
Step 13: Open the build.gradle file in the android directory of your Flutter project.
Step 14: Configure the Maven repository address for the HMS Core SDK in your allprojects.
Step 15: Open the build.gradle file in the android > app directory of your Flutter project. Add apply plugin: 'com.huawei.agconnect' after other apply entries.
Step 16: Set minSdkVersion to 19 or higher in defaultConfig.
Add dependencies
implementation 'com.huawei.hms:hwid:4.0.4.300'
Step: 18: Add internet permission in the manifest.
1<uses-permission android:name="android.permission.INTERNET" />
Step 17: Build Flutter sample Application.
Rita: Thanks man. Really integration is so easy.
Me: Yeah.
Rita: Hey you did not explain more about features of Account kit.
Me: Oh, yeah I forgot to explain about it, let me explain. As you already know what are features, so let me explain one by one.
Sign In: The signIn method is used to obtain the intent of the HUAWEI ID sign-in authorization page. It takes an HmsAuthParamHelper object as a parameter which is optional. This parameter allows you to customize the sign-in request. When this method is called, an authorization page shows up. After a user successfully signs in using a HUAWEI ID, the HUAWEI ID information is obtained through the HmsAuthHuaweiId object.
Me: Add button or image in application and on tap of button use the below code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30void signInWithHuaweiAccount() async {
HmsAuthParamHelper authParamHelper = new HmsAuthParamHelper();
authParamHelper
..setIdToken()
..setAuthorizationCode()
..setAccessToken()
..setProfile()
..setEmail()
..setScopeList([HmsScope.openId, HmsScope.email, HmsScope.profile])
..setRequestCode(8888);
try {
final HmsAuthHuaweiId accountInfo =
await HmsAuthService.signIn(authParamHelper: authParamHelper);
setState(() {
var accountDetails = AccountInformation(accountInfo.displayName,
accountInfo.email, accountInfo.givenName, accountInfo.familyName, accountInfo.avatarUriString);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Homepage(
accountInformation: accountDetails,
),
));
print("account name: " + accountInfo.displayName);
});
} on Exception catch (exception) {
print(exception.toString());
print("error: " + exception.toString());
}
}
Silent Sign In: The silentSignIn method is used to obtain the HUAWEI ID that has been used to sign in to the app. In this process, the authorization page is not displayed to the HUAWEI ID user. The method takes an HmsAuthParamHelper object as a parameter which is optional, returns an HmsAuthHuaweiId object upon a successful operation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19void silentSignInHuaweiAccount() async {
HmsAuthParamHelper authParamHelper = new HmsAuthParamHelper();
try {
final HmsAuthHuaweiId accountInfo =
await HmsAuthService.silentSignIn(authParamHelper: authParamHelper);
if (accountInfo.unionId != null) {
print("Open Id: ${accountInfo.openId}");
print("Display name: ${accountInfo.displayName}");
print("Profile DP: ${accountInfo.avatarUriString}");
print("Email Id: ${accountInfo.email}");
Validator()
.showToast("Signed in successful as ${accountInfo.displayName}");
}
} on Exception catch (exception) {
print(exception.toString());
print('Login_provider:Can not SignIn silently');
Validator().showToast("SCan not SignIn silently ${exception.toString()}");
}
}
Sign Out: The signOut method is called to sign out from a HUAWEI ID.
1
2
3
4
5
6
7
8
9
10Future signOut() async {
final signOutResult = await HmsAuthService.signOut();
if (signOutResult) {
Validator().showToast("Signed out successful");
Route route = MaterialPageRoute(builder: (context) => SignInPage());
Navigator.pushReplacement(context, route);
} else {
print('Login_provider:signOut failed');
}
}
Revoke Authorization: The revokeAuthorization method is used to cancel the authorization from the HUAWEI ID user. All user data will be removed after this method is called. On another signing-in attempt, the authorization page is displayed.
1
2
3
4
5
6
7
8Future revokeAuthorization() async {
final bool revokeResult = await HmsAuthService.revokeAuthorization();
if (revokeResult) {
Validator().showToast("Revoked Auth Successfully");
} else {
Validator().showToast('Login_provider:Failed to Revoked Auth');
}
}
Rita: Great…
Me: Thank you.
Rita: Do you have any application to see how it looks?
Me: Yes I’m building an application for taxi booking in that I have integrated account kit you see that.
Rita: Can you show how it looks?
Me: Off course. Check how it looks in result section?
Result
Sign In and Sign Out.
Silent Sign In.
Revoke authorization.
Rita: Looking nice!
Rita: Hey should I remember any key points in this account kit.
Me: Yes, let me give you some tips and tricks.
Tips and Tricks
Make sure you are already registered as Huawei developer.
Enable Account kit service in the App Gallery.
Make sure your HMS Core is latest version.
Make sure you added the agconnect-services.json file to android/app folder.
Make sure click on Pub get.
Make sure all the dependencies are downloaded properly.
Rita: Really, thank you so much for your explanation.
Me: I hope now you can integrate Account kit in flutter right?
Rita: Yes, I Can.
Me: Than can I conclude on this account kit?
Rita: Yes, please
Conclusion
In this chat conversation, we have learnt how to integrate Account kit in Flutter. Following topics are covered in the article.
1. What exactly Account kit is.
2. Benefits of account kit.
3. Time required to integrate.
4. Integration of account kit in the flutter.
Girlfriend: Can I get some reference link?
Me: Follow the below reference.
Reference
Account Kit official document
Account kit Flutter package
Happy coding
Related
In this article, you guys can read how I had conversation with my girlfriend about Account kit integration in the Flutter.
Rita: Hey, Happy morning.
Me: Happy morning.
Rita: I heard that Huawei supports Account kit in flutter. Does it really support? Do you have any idea about it?
Me: Yes it supports. I’ve idea about account kit in flutter.
Rita: That’s great, can you explain me?
Me: Why not definitely.
Me: But what exactly you want to know about account kit in flutter?
Rita: I have couple of question check below questions.
1. What is account kit?
2. What is the benefit of account kit?
3. How much time it takes to integrate in flutter?
4. How to integrate Huawei account kit in flutter?
Me: OMG so many questions. I should rename your name to Question bank instead of your name. But fine I’ll answer all your questions. Let me answer one by one.
Rita: Okay.
Me: Here is your answer for first question.
What is account kit?
To answer this question let me give introduction about account kit.
Introduction
Huawei Account Kit is a development kit and account service developed by Huawei. Easy to integrate Sign In-based functions into your applications. It save user’s long authorization period and also two factor authorization user information is very safe. Flutter account kit plugin allows users to connect with Huawei Ecosystem using Huawei IDs. It supports both mobiles and tablets. User can sign any application from Huawei account.
Rita: Awesome introduction (@Reader its self-compliment. If you have any questions/compliments/comments about account kit in flutter. I’m expecting it in comments section.)
Me: I hope now you got answer for what is account kit?
Rita: Yes, I got it.
Me: Let’s move to next question
What is the benefit of account kit?
Me: Before answering this question, let me ask you one question. How do you sign up for application?
Rita: Traditional way.
Me: Traditional way means?
Rita: I’ll ask user information in the application.
Me: Okay, let me explain you one scenario, if you are referring same thing let me know.
Rita: Fine
Me: Being a developer, what we usually do is we collect user information in sign up screen manually. User first name, last name, email id, mobile number, profile picture etc. These are the basic information required to create account. Let me share you one screen.
{
"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"
}
Me: This is how you ask for sign up right?
Rita: Exactly you are right, I’m referring same things.
Me: See in this traditional way user has to enter everything manually it is very time consuming. You know nowadays users are very specific about time. User needs everything in one click for that, being a developer we need to fulfill user requirement. So Huawei built a Flutter plugin for account kit to overcome the above situation.
Me: Now you got the problem right?
Rita: Yes.
Me: So, to avoid above situation you can sign up using Huawei account kit and get user information in one click more over user information is safe.
Me: I hope I have answered your question what is the benefit of account kit?
Rita: Yes
Me: Now let me explain about features of Account Kit.
Features of Account kit
1. Sign in
2. Silent sign in
3. Sign out
4. Revoke authorization.
Me: Now let’s move to next question.
How much time it takes to integrate in flutter?
Me: this is very simple question it hardly takes 10 minutes.
Rita: Oh is it? It means Integration will be very easy.
Me: Yes, you are clever.
Rita: ha ha ha. I’m not clever Huawei made it very easy, I just guessed it.
Me: Okay, are you getting bored?
Rita: No, why?
Me: If you are bored, I just wanted to crack a joke.
Rita: Joke? That’s too from you? No buddy because I’ll get confuse where to laugh and you know sometimes I don’t even get you have finished your joke.
Me: Everybody says the same thing.
Rita: Then imagine, how bad you in joke.
Me: Okay Okay, lets come back to concept (In angry).
Rita: Don’t get angry man I’m in mood of learning not in mood of listening joke.
Me: Okay, let’s move to next question.
How to integrate Huawei account kit in flutter?
To answer your question follow the steps.
Step 1: Register as a Huawei Developer. If you have already a Huawei developer account ignore this step.
Step 2: Create a Flutter application in android studio or any other IDE.
Step 3: Generate Signing certificate fingerprint.
Step 4: Download Account Kit Flutter package and decompress it.
Step 5: Add dependencies pubspec.yaml. Change path according to your downloaded path.
Step 6: After adding the dependencies, click on Pub get.
Step 7: Navigate to any of the *.dart file and click on Get dependencies.
Step 8: Sign in to AppGallery Connect and select My projects.
Step 9: Click your project from the project list.
Step 10: Navigate to Project Setting > General information and click Add app.
Step 11: Navigate to Manage API and Enable Account kit.
Step 12: Download agconnect-services.json and paste in android/app folder.
Step 13: Open the build.gradle file in the android directory of your Flutter project.
Step 14: Configure the Maven repository address for the HMS Core SDK in your allprojects.
Step 15: Open the build.gradle file in the android > app directory of your Flutter project. Add apply plugin: 'com.huawei.agconnect' after other apply entries.
Step 16: Set minSdkVersion to 19 or higher in defaultConfig.
Add dependencies
1implementation 'com.huawei.hms:hwid:4.0.4.300'
Step: 18: Add internet permission in the manifest.
Java:
<uses-permission android:name="android.permission.INTERNET" />
Step 17: Build Flutter sample Application.
Rita: Thanks man. Really integration is so easy.
Me: Yeah.
Rita: Hey you did not explain more about features of Account kit.
Me: Oh, yeah I forgot to explain about it, let me explain. As you already know what are features, so let me explain one by one.
Sign In: The signIn method is used to obtain the intent of the HUAWEI ID sign-in authorization page. It takes an HmsAuthParamHelper object as a parameter which is optional. This parameter allows you to customize the sign-in request. When this method is called, an authorization page shows up. After a user successfully signs in using a HUAWEI ID, the HUAWEI ID information is obtained through the HmsAuthHuaweiId object.
Me: Add button or image in application and on tap of button use the below code.
Java:
void signInWithHuaweiAccount() async {
HmsAuthParamHelper authParamHelper = new HmsAuthParamHelper();
authParamHelper
..setIdToken()
..setAuthorizationCode()
..setAccessToken()
..setProfile()
..setEmail()
..setScopeList([HmsScope.openId, HmsScope.email, HmsScope.profile])
..setRequestCode(8888);
try {
final HmsAuthHuaweiId accountInfo =
await HmsAuthService.signIn(authParamHelper: authParamHelper);
setState(() {
var accountDetails = AccountInformation(accountInfo.displayName,
accountInfo.email, accountInfo.givenName, accountInfo.familyName, accountInfo.avatarUriString);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Homepage(
accountInformation: accountDetails,
),
));
print("account name: " + accountInfo.displayName);
});
} on Exception catch (exception) {
print(exception.toString());
print("error: " + exception.toString());
}
}
Silent Sign In: The silentSignIn method is used to obtain the HUAWEI ID that has been used to sign in to the app. In this process, the authorization page is not displayed to the HUAWEI ID user. The method takes an HmsAuthParamHelper object as a parameter which is optional, returns an HmsAuthHuaweiId object upon a successful operation.
Java:
void silentSignInHuaweiAccount() async {
HmsAuthParamHelper authParamHelper = new HmsAuthParamHelper();
try {
final HmsAuthHuaweiId accountInfo =
await HmsAuthService.silentSignIn(authParamHelper: authParamHelper);
if (accountInfo.unionId != null) {
print("Open Id: ${accountInfo.openId}");
print("Display name: ${accountInfo.displayName}");
print("Profile DP: ${accountInfo.avatarUriString}");
print("Email Id: ${accountInfo.email}");
Validator()
.showToast("Signed in successful as ${accountInfo.displayName}");
}
} on Exception catch (exception) {
print(exception.toString());
print('Login_provider:Can not SignIn silently');
Validator().showToast("SCan not SignIn silently ${exception.toString()}");
}
}
Sign Out: The signOut method is called to sign out from a HUAWEI ID.
Java:
Future signOut() async {
final signOutResult = await HmsAuthService.signOut();
if (signOutResult) {
Validator().showToast("Signed out successful");
Route route = MaterialPageRoute(builder: (context) => SignInPage());
Navigator.pushReplacement(context, route);
} else {
print('Login_provider:signOut failed');
}
}
Revoke Authorization: The revokeAuthorization method is used to cancel the authorization from the HUAWEI ID user. All user data will be removed after this method is called. On another signing-in attempt, the authorization page is displayed.
Java:
Future revokeAuthorization() async {
final bool revokeResult = await HmsAuthService.revokeAuthorization();
if (revokeResult) {
Validator().showToast("Revoked Auth Successfully");
} else {
Validator().showToast('Login_provider:Failed to Revoked Auth');
}
}
Rita: Great…
Me: Thank you.
Rita: Do you have any application to see how it looks?
Me: Yes I’m building an application for taxi booking in that I have integrated account kit you see that.
Rita: Can you show how it looks?
Me: Off course. Check how it looks in result section?
Result
Sign In and Sign Out.
Silent Sign In.
Revoke authorization.
Rita: Looking nice!
Rita: Hey should I remember any key points in this account kit.
Me: Yes, let me give you some tips and tricks.
Tips and Tricks
Make sure you are already registered as Huawei developer.
Enable Account kit service in the App Gallery.
Make sure your HMS Core is latest version.
Make sure you added the agconnect-services.json file to android/app folder.
Make sure click on Pub get.
Make sure all the dependencies are downloaded properly.
Rita: Really, thank you so much for your explanation.
Me: I hope now you can integrate Account kit in flutter right?
Rita: Yes, I Can.
Me: Than can I conclude on this account kit?
Rita: Yes, please
Conclusion
In this chat conversation, we have learnt how to integrate Account kit in Flutter. Following topics are covered in the article.
1. What exactly Account kit is.
2. Benefits of account kit.
3. Time required to integrate.
4. Integration of account kit in the flutter.
Girlfriend: Can I get some reference link?
Me: Follow the below reference.
Reference
Account Kit official document
Account kit Flutter package
Happy coding
{
"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"
}
In this article, you guys can read how I had conversation with my girlfriend about Account kit integration in the Flutter.
Rita: Hey, Happy morning.
Me: Happy morning.
Rita: I heard that Huawei supports Account kit in flutter. Does it really support? Do you have any idea about it?
Me: Yes it supports. I’ve idea about account kit in flutter.
Rita: That’s great, can you explain me?
Me: Why not definitely.
Me: But what exactly you want to know about account kit in flutter?
Rita: I have couple of question check below questions.
1. What is account kit?
2. What is the benefit of account kit?
3. How much time it takes to integrate in flutter?
4. How to integrate Huawei account kit in flutter?
Me: OMG so many questions. I should rename your name to Question bank instead of your name. But fine I’ll answer all your questions. Let me answer one by one.
Rita: Okay.
Me: Here is your answer for first question.
What is account kit?
To answer this question let me give introduction about account kit.
Introduction
Huawei Account Kit is a development kit and account service developed by Huawei. Easy to integrate Sign In-based functions into your applications. It save user’s long authorization period and also two factor authorization user information is very safe. Flutter account kit plugin allows users to connect with Huawei Ecosystem using Huawei IDs. It supports both mobiles and tablets. User can sign any application from Huawei account.
Rita: Awesome introduction (@Reader its self-compliment. If you have any questions/compliments/comments about account kit in flutter. I’m expecting it in comments section.)
Me: I hope now you got answer for what is account kit?
Rita: Yes, I got it.
Me: Let’s move to next question
What is the benefit of account kit?
Me: Before answering this question, let me ask you one question. How do you sign up for application?
Rita: Traditional way.
Me: Traditional way means?
Rita: I’ll ask user information in the application.
Me: Okay, let me explain you one scenario, if you are referring same thing let me know.
Rita: Fine
Me: Being a developer, what we usually do is we collect user information in sign up screen manually. User first name, last name, email id, mobile number, profile picture etc. These are the basic information required to create account. Let me share you one screen.
Me: This is how you ask for sign up right?
Rita: Exactly you are right, I’m referring same things.
Me: See in this traditional way user has to enter everything manually it is very time consuming. You know nowadays users are very specific about time. User needs everything in one click for that, being a developer we need to fulfill user requirement. So Huawei built a Flutter plugin for account kit to overcome the above situation.
Me: Now you got the problem right?
Rita: Yes.
Me: So, to avoid above situation you can sign up using Huawei account kit and get user information in one click more over user information is safe.
Me: I hope I have answered your question what is the benefit of account kit?
Rita: Yes
Me: Now let me explain about features of Account Kit.
Features of Account kit
1. Sign in
2. Silent sign in
3. Sign out
4. Revoke authorization.
Me: Now let’s move to next question.
How much time it takes to integrate in flutter?
Me: this is very simple question it hardly takes 10 minutes.
Rita: Oh is it? It means Integration will be very easy.
Me: Yes, you are clever.
Rita: ha ha ha. I’m not clever Huawei made it very easy, I just guessed it.
Me: Okay, are you getting bored?
Rita: No, why?
Me: If you are bored, I just wanted to crack a joke.
Rita: Joke? That’s too from you? No buddy because I’ll get confuse where to laugh and you know sometimes I don’t even get you have finished your joke.
Me: Everybody says the same thing.
Rita: Then imagine, how bad you in joke.
Me: Okay Okay, lets come back to concept (In angry).
Rita: Don’t get angry man I’m in mood of learning not in mood of listening joke.
Me: Okay, let’s move to next question.
How to integrate Huawei account kit in flutter?
To answer your question follow the steps.
Step 1: Register as a Huawei Developer. If you have already a Huawei developer account ignore this step.
Step 2: Create a Flutter application in android studio or any other IDE.
Step 3: Generate Signing certificate fingerprint.
Step 4: Download Account Kit Flutter package and decompress it.
Step 5: Add dependencies pubspec.yaml. Change path according to your downloaded path.
Step 6: After adding the dependencies, click on Pub get.
Step 7: Navigate to any of the *.dart file and click on Get dependencies.
Step 8: Sign in to AppGallery Connect and select My projects.
Step 9: Click your project from the project list.
Step 10: Navigate to Project Setting > General information and click Add app.
Step 11: Navigate to Manage API and Enable Account kit.
Step 12: Download agconnect-services.json and paste in android/app folder.
Step 13: Open the build.gradle file in the android directory of your Flutter project.
Step 14: Configure the Maven repository address for the HMS Core SDK in your allprojects.
Step 15: Open the build.gradle file in the android > app directory of your Flutter project. Add apply plugin: 'com.huawei.agconnect' after other apply entries.
Step 16: Set minSdkVersion to 19 or higher in defaultConfig.
Add dependencies
implementation 'com.huawei.hms:hwid:4.0.4.300'
Step: 18: Add internet permission in the manifest.
1<uses-permission android:name="android.permission.INTERNET" />
Step 17: Build Flutter sample Application.
Rita: Thanks man. Really integration is so easy.
Me: Yeah.
Rita: Hey you did not explain more about features of Account kit.
Me: Oh, yeah I forgot to explain about it, let me explain. As you already know what are features, so let me explain one by one.
Sign In: The signIn method is used to obtain the intent of the HUAWEI ID sign-in authorization page. It takes an HmsAuthParamHelper object as a parameter which is optional. This parameter allows you to customize the sign-in request. When this method is called, an authorization page shows up. After a user successfully signs in using a HUAWEI ID, the HUAWEI ID information is obtained through the HmsAuthHuaweiId object.
Me: Add button or image in application and on tap of button use the below code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30void signInWithHuaweiAccount() async {
HmsAuthParamHelper authParamHelper = new HmsAuthParamHelper();
authParamHelper
..setIdToken()
..setAuthorizationCode()
..setAccessToken()
..setProfile()
..setEmail()
..setScopeList([HmsScope.openId, HmsScope.email, HmsScope.profile])
..setRequestCode(8888);
try {
final HmsAuthHuaweiId accountInfo =
await HmsAuthService.signIn(authParamHelper: authParamHelper);
setState(() {
var accountDetails = AccountInformation(accountInfo.displayName,
accountInfo.email, accountInfo.givenName, accountInfo.familyName, accountInfo.avatarUriString);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Homepage(
accountInformation: accountDetails,
),
));
print("account name: " + accountInfo.displayName);
});
} on Exception catch (exception) {
print(exception.toString());
print("error: " + exception.toString());
}
}
Silent Sign In: The silentSignIn method is used to obtain the HUAWEI ID that has been used to sign in to the app. In this process, the authorization page is not displayed to the HUAWEI ID user. The method takes an HmsAuthParamHelper object as a parameter which is optional, returns an HmsAuthHuaweiId object upon a successful operation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19void silentSignInHuaweiAccount() async {
HmsAuthParamHelper authParamHelper = new HmsAuthParamHelper();
try {
final HmsAuthHuaweiId accountInfo =
await HmsAuthService.silentSignIn(authParamHelper: authParamHelper);
if (accountInfo.unionId != null) {
print("Open Id: ${accountInfo.openId}");
print("Display name: ${accountInfo.displayName}");
print("Profile DP: ${accountInfo.avatarUriString}");
print("Email Id: ${accountInfo.email}");
Validator()
.showToast("Signed in successful as ${accountInfo.displayName}");
}
} on Exception catch (exception) {
print(exception.toString());
print('Login_provider:Can not SignIn silently');
Validator().showToast("SCan not SignIn silently ${exception.toString()}");
}
}
Sign Out: The signOut method is called to sign out from a HUAWEI ID.
1
2
3
4
5
6
7
8
9
10Future signOut() async {
final signOutResult = await HmsAuthService.signOut();
if (signOutResult) {
Validator().showToast("Signed out successful");
Route route = MaterialPageRoute(builder: (context) => SignInPage());
Navigator.pushReplacement(context, route);
} else {
print('Login_provider:signOut failed');
}
}
Revoke Authorization: The revokeAuthorization method is used to cancel the authorization from the HUAWEI ID user. All user data will be removed after this method is called. On another signing-in attempt, the authorization page is displayed.
1
2
3
4
5
6
7
8Future revokeAuthorization() async {
final bool revokeResult = await HmsAuthService.revokeAuthorization();
if (revokeResult) {
Validator().showToast("Revoked Auth Successfully");
} else {
Validator().showToast('Login_provider:Failed to Revoked Auth');
}
}
Rita: Great…
Me: Thank you.
Rita: Do you have any application to see how it looks?
Me: Yes I’m building an application for taxi booking in that I have integrated account kit you see that.
Rita: Can you show how it looks?
Me: Off course. Check how it looks in result section?
Result
Sign In and Sign Out.
Silent Sign In.
Revoke authorization.
Rita: Looking nice!
Rita: Hey should I remember any key points in this account kit.
Me: Yes, let me give you some tips and tricks.
Tips and Tricks
Make sure you are already registered as Huawei developer.
Enable Account kit service in the App Gallery.
Make sure your HMS Core is latest version.
Make sure you added the agconnect-services.json file to android/app folder.
Make sure click on Pub get.
Make sure all the dependencies are downloaded properly.
Rita: Really, thank you so much for your explanation.
Me: I hope now you can integrate Account kit in flutter right?
Rita: Yes, I Can.
Me: Than can I conclude on this account kit?
Rita: Yes, please
Conclusion
In this chat conversation, we have learnt how to integrate Account kit in Flutter. Following topics are covered in the article.
1. What exactly Account kit is.
2. Benefits of account kit.
3. Time required to integrate.
4. Integration of account kit in the flutter.
Girlfriend: Can I get some reference link?
Me: Follow the below reference.
Reference
Account Kit official document
Account kit Flutter package
Happy coding
Introduction
Huawei provides various services for developers to come up with the solution for the problems which we are facing in our everyday life.
Problem: We have researched and found out that some people do have sight problems due to age and because of that they cannot read the text on the screen clearly, but they love to read news every day. Keeping that in mind we come up with a solution.
Solution: Using Huawei Mobile Service (HMS) core kits, we have tried to integrate as many kits as possible and created a smart but very effective news application.
In this News Application user can login, read or listen to the latest news and also user can change the default app language to their own native language. User will also receive notification messages based on the topic they subscribed on regular basis.
Let’s look into the Kits we have integrated in our Smart News App:
1. Account Kit
2. Ads Kit
3. ML Kit
4. Push Kit
5. Crash Service
This application will be explained in two parts:
1. In part one, I will explain how to integrate Account Kit and Ads Kit.
2. In part two, I will explain how to integrate ML Kit and Push Kit.
Demo
We will be focusing only on Account Kit and Ads Kit demo in this part.
{
"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"
}
Prerequisites
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.
Integration Preparations
1. First we need to create a project in android studio.
2. Generate a SHA-256 certificate fingerprint. To generate SHA-256 certificate fingerprint use below command.
Code:
keytool -list -v -keystore
D:\SmartNewsApp\file_name.keystore
-alias alias_name.
3. Create a project in AppGallery Connect.
4. Enable Account kit and Ads Kit in Manage APIs section.
5. Provide the SHA Key in App Information Section.
6. Provide storage location.
7. Download the agconnect-services.json, copy and paste the Json file in the app folder.
8. Copy and paste the below maven URL inside the repositories of buildscript and allprojects (project build.gradle file).
Java:
maven { url 'http://developer.huawei.com/repo/' }
9. Copy and paste the below plugin in the app build.gradle file.
Java:
apply plugin: 'com.huawei.agconnect'
10. After that, we need to add dependencies into build.gradle files.
Java:
implementation 'com.huawei.hms:hwid:5.0.3.301' //Account Kit
implementation 'com.huawei.hms:ads-lite:13.4.34.301' //Ads Kit
Now, we need to sync our build.gradle files.
Account Kit Overview
HUAWEI Account Kit provides developers with simple, secure, and quick sign-in and authorization functions. Instead of entering accounts and passwords and waiting for authorization, users can just tap the Sign In with HUAWEI ID button to quickly and securely sign in to the app.
We will implement authorization code sign in use case for login scenario in this application.
Let’s start the coding!
Signing with Authorization Code
Add the below code in activity_main.xml.
XML:
<com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/hwi_sign_in"
android:layout_gravity="center_horizontal|center_vertical"
android:visibility="visible"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:background="#3b5998"
app:hwid_button_theme="hwid_button_theme_full_title"
app:hwid_corner_radius="hwid_corner_radius_small"/>
Huawei id auth button component is used here. Please check for getting more information about usage of Huawei ID signing in button.
Add the below code in LoginActivity.java
Java:
HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().setEmail().createParams();
HuaweiIdAuthService service = HuaweiIdAuthManager.getService(MainActivity.this, authParams);
startActivityForResult(service.getSignInIntent(), Constants.HUAWEI_SIGNIN);
When we click the Huawei ID signing in button, it needs the HuaweiIdAuthParams and create a service with authParams. Then, we call startActivityForResult() method in Huawei ID signing in button click with service and HUAWEI_SIGNIN constant. The constant (HUAWEI_SIGNIN) uses for handling the requestCode in onActivityResult() method. When the user clicks login with Huawei ID button, the app needs to authorize and login operations from the user.
Java:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// Process the authorization result and obtain the authorization code from AuthHuaweiId.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.REQUEST_CODE) {
Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
if (authHuaweiIdTask.isSuccessful()) {
// The sign-in is successful, and the user's HUAWEI ID information and authorization code are obtained.
AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
String name = huaweiAccount.getDisplayName();
String email = huaweiAccount.getEmail();
SharedPreferences.Editor editor = getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("login", true);
editor.putString("name", name);
editor.putString("email", email);
editor.apply();
editor.commit();
Intent intent = new Intent(MainActivity.this, NewsActivity.class);
startActivity(intent);
} else {
// The sign-in failed.
Log.e(TAG, getApplication().getResources().getString(R.string.sigin_failed));
Toast.makeText(this, getApplicationContext().getResources().getString(R.string.unable_to_login), Toast.LENGTH_LONG).show();
}
}
}
When the user is signed in successfully and we could able to get users name and profile picture, email address and etc. It is displayed in the user profile.
Add the below code in UserProfile.java class.
Java:
signout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setIdToken().createParams();
HuaweiIdAuthService service= HuaweiIdAuthManager.getService(About.this, authParams) ;
Task<Void> signOutTask = service.signOut();
signOutTask.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
// Processing after the sign-out.
finishAndRemoveTask();
}
});
}
});
Ads Kits Overview
The most common method used by mobile developers is to generate revenue from their application is to create advertising spaces for advertisers. Advertisers prefer to place their ads through mobile media rather than printed publications.In this sense, Huawei Ads meets the requirement of both advertisers and mobile developers.
HMS Ads Kit is a mobile service that helps us to create high quality and personalized ads in our application.
Currently, HMS contains 7 kind of ads kits. In this application we will be integrating Banner ads.
Adding a Banner Ad
Add the following lines to your app level build.gradle file.
Java:
implementation 'com.huawei.hms:ads-lite:13.4.34.301'
Add BannerView to the XML layout file. Set the hwads:adId for the ad slot ID and hwads:bannerSize for the ad size.
XML:
<com.huawei.hms.ads.banner.BannerView android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/hw_banner_view"
app:bannerSize="BANNER_SIZE_360_57" app:adId="testw6vs28auh3"
android:layout_alignParentBottom="true"/>
Note: Various banner size is available.
After creating the BannerView in XML file, call it from your class and load the banner ad. In this application we are displaying banner ads after every news in the newslist. So we have added in NewsListAdapter class.
Add the below code in NewsListAdapter class.
Java:
BannerView bottomBannerView = itemView.findViewById(R.id.hw_banner_view);
rootView = itemView.findViewById(R.id.root_view);
AdParam adParam = new AdParam.Builder().build();
RelativeLayout bottomBannerView.loadAd(adParam);
// Call new BannerView(Context context) to create a BannerView class.
BannerView topBannerView = new BannerView(context);
topBannerView.setBannerAdSize(BannerAdSize.BANNER_SIZE_360_57);
topBannerView.loadAd(adParam);
rootView.addView(topBannerView);
Tips and Tricks
1. Add agconnect-services.json file without fail.
2. Add SHA-256 fingerprint without fail.
3. Make sure dependencies added in build files.
4. Banner ads be can also added programmatically.
Conclusion
You may find some problems in your surroundings and I hope you can come up with a solution for those problems using HMS core kits.
Thanks for reading the article, please do like and comment your queries or suggestions.
References
HMS Account Kit
HMS Ads Kit
Read In Forum
Introduction
In this article, I will talk about that how Flutter project integrates Huawei kits, and learn how to use them in your Flutter projects. Apps are tested many times before they released, but still crashes are there. There is a Huawei Crash Service to minimize these risks. Learning app which highlights recommended courses and Topic based courses, here I will cover below kits.
1. IAP kit
2. Crash Service
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. A little knowledge of Dart and Flutter.
4. Minimum API Level 24 is required.
5. Required EMUI 5.0 and later version devices.
Setting up the Project
1. First create a developer account in AppGallery Connect. After create your developer account, you can create a new project and new app. For more information, click here
2. Generating a Signing certificate fingerprint, follow the command
Code:
keytool -genkey -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks -storepass <store_password> -alias <alias> -keypass <key_password> -keysize 2048 -keyalg RSA -validity 36500
3. The above command creates the keystore file in appdir/android/app.
4. Now we need to obtain the SHA256 key. Follow the command
Code:
keytool -list -v -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks
5. Now you need to apply for merchant service and enable IAP. To enable Merchant Service, Choose My Projects > Manage APIs > In-App Purchases. You will be asked to apply for Merchant Service. Here, you’ll need to enter your bank information and go through a review process. This review process can take up to 2 days.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
6. Once Merchant service activated, Navigate to Earning > In-App Purchases if this is the first time, then you need to sign the agreement.
7. After the configuration is successful, the page displays the public key used for subsequent payment signature verification and a parameter for configuring the subscription notification URL.
8. We need Sandbox account in order to test the IAP. Navigate to App Gallery > Users and Permissions > Sandbox >Test account.
9. We have to enable Analytics to use Crash Service. Navigate to App Gallery > Huawei Analytics. The Analytics page is displayed.
10. We have to enable the Crash service, Navigate to Quality > Crash and enable Crash service.
11. After configuring project, we need to download agconnect-services.json file in your project and add into your project.
12. After that follow the URL for cross-platform plugins. Download required plugins.
13. The following dependencies for HMS usage need to be added to build.gradle file under the android directory.
Code:
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'}
}
}
14. Add the below plugin in build.gradle file under the android/app directory.
Code:
apply plugin: 'com.huawei.agconnect'
15. Add the required permissions in AndroidManifest.xml file under app/src/main folder.
XML:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
16. 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_iap:
path: ../huawei_iap/
agconnect_crash: ^1.1.0
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 that app will not crash.
IAP Kit Introduction
In-app purchases can be used to sell a variety of content through your app, including subscriptions, new features, and services. Users can make in-app purchases on all sorts of devices and operating systems — not just their mobile phones.
There are 4 types of in-app purchases available in Huawei IAP Kit.
Consumables: Users can purchase different types of consumables, such as extra lives or gems in a game, to further their progress through an app. Consumable in-app purchases are used once, are depleted, and can be purchased again.
Non-Consumables: Users can purchase non-consumable, premium features within an app, such as additional filters in a photo app. Non-consumables are purchased once and do not expire.
Auto-Renewable Subscriptions: Users can purchase access to services or periodically updated content, such as monthly access to cloud storage or a weekly subscription to a magazine. Users are charged on a recurring basis until they decide to cancel.
Non-Renewing Subscriptions: Users can purchase access to services or content for a limited time, such as a season pass to streaming content. This type of subscription does not renew automatically, so users need to renew at the end of each subscription period.
How to Configure Product info
To add product, Navigate to My Apps > Learning app > Operate > Product operation > Product management. Click Products tab and click Add product. Configure Product information and click Save.
Now we successfully added consumable products, we need to activate the product.
Let’s implement code
First we need to check whether environment and sandbox account is ready.
YAML:
checkEnv() async {
isEnvReadyStatus = null;
try {
IsEnvReadyResult response = await IapClient.isEnvReady();
isEnvReadyStatus = response.status.statusMessage;
if (isEnvReadyStatus != null) {
checkSandboxAccount();
}
} on PlatformException catch (e) {
if (e.code == HmsIapResults.LOG_IN_ERROR.resultCode) {
print(HmsIapResults.LOG_IN_ERROR.resultMessage);
} else {
print(e.toString());
}
}
}
checkSandboxAccount() async {
isSandBoxStatus = null;
try {
IsSandboxActivatedResult result = await IapClient.isSandboxActivated();
isSandBoxStatus = result.status.statusMessage;
} on PlatformException catch (e) {
if (e.code == HmsIapResults.LOG_IN_ERROR.resultCode) {
print(HmsIapResults.LOG_IN_ERROR.resultMessage);
} else {
print(e.toString());
}
}
}
Fetch products
Use the obtainProductInfo API to get details of in-app products configured in AppGallery Connect.
Perform the following development steps
Construct a ProductInfoReq object to get ProductInfo.
Pass the Product ID that was defined and effective in AppGallery Connect to the ProductInfoReq object and specify the priceType for a product
YAML:
fetchConsumable() async {
try {
ProductInfoReq req = new ProductInfoReq();
req.priceType = IapClient.IN_APP_CONSUMABLE;
req.skuIds = ["ED_1011"];
ProductInfoResult res = await IapClient.obtainProductInfo(req);
consumable = [];
for (int i = 0; i < res.productInfoList.length; i++) {
consumable.add(res.productInfoList[i]);
}
} on PlatformException catch (e) {
if (e.code == HmsIapResults.ORDER_HWID_NOT_LOGIN.resultCode) {
print(HmsIapResults.ORDER_HWID_NOT_LOGIN.resultMessage);
} else {
print(e.toString());
}
}
}
Purchase products
You can initiate a purchase request through the createPurchaseIntent API. Call createPurchaseIntent with the appropriate parameters to automatically display the HUAWEI IAP payment page.
YAML:
subscribeProduct(String productID) async {
PurchaseIntentReq request = PurchaseIntentReq();
request.priceType = IapClient.IN_APP_CONSUMABLE;
request.productId = productID;
request.developerPayload = "Course";
try {
PurchaseResultInfo result = await IapClient.createPurchaseIntent(request);
if (result.returnCode == HmsIapResults.ORDER_STATE_SUCCESS.resultCode) {
log("Successfully plan subscribed");
} else if (result.returnCode ==
HmsIapResults.ORDER_STATE_FAILED.resultCode) {
log("Product subscription failed");
} else if (result.returnCode ==
HmsIapResults.ORDER_STATE_CANCEL.resultCode) {
log("User cancel the payment");
} else if (result.returnCode ==
HmsIapResults.ORDER_PRODUCT_OWNED.resultCode) {
log("Already Product subscribed");
} else {
log(result.errMsg);
}
} on PlatformException catch (e) {
if (e.code == HmsIapResults.ORDER_HWID_NOT_LOGIN.resultCode) {
log(HmsIapResults.ORDER_HWID_NOT_LOGIN.resultMessage);
} else {
log(e.toString());
}
}
}
Crash Service Introduction
This service help us to minimize these crash risks. Also this service integration is relatively simple and doesn’t require coding. The Crash Service provides crash reports which are easy to reference and analyze.
Huawei Crash Service provides a powerful yet lightweight solution to app crash problems. With the service, you can quickly detect, locate, and resolve app crashes (unexpected exits of apps), and have access to highly readable crash reports in real time, without the required to write any code.
Crash Service provides some various features
1. The last-hour crash report allows you to monitor the quality of your app in real time.
2. The Crash service automatically categorizes crashes, and provides indicator data of the crashes allowing you to prioritize the most important crashes.
3. You can view information about a specific crash, and analyze the app and Android versions with the crash.
4. You can also view information about the app, operating system, and device corresponding to a specific crash, as well as the crashed stack.
5. The Crash service can also detect major crashes in real time. After you enable crash notifications, App Gallery Connect can send you an email when a major crash occurs.
To create a crash we have a AGCCrash.instance().testIt() method. By calling it we can crash our app. On button click add this method and crash your app
Code:
Positioned(
top:30,
child: Container(
child: IconButton(
onPressed: (){
AGCCrash.instance.testIt();// To test crash
},
icon: Icon(Icons.arrow_back,color: Colors.white,),
),
),
)
We also have custom report methods such as setUserId, log, setCustomValue and so on. In this example I created a test button Custom Report in ViewController class. You can click the button to call the setUserId method to set the user ID, the log:level method to record logs, and the setCustomValue:value method to add custom key-value pairs.
Code:
void handleCrash() async{
await AGCCrash.instance.enableCrashCollection(true);
AGCCrash.instance.setUserId("11223344");
AGCCrash.instance.setCustomKey("Huawei", "Reporting crashed"); AGCCrash.instance.log(level: LogLevel.debug,message: "Crash has successfully reported.");
}
How we can check crash Report
Crash Service automatically reports the occurred crashes to AppGallery Connect. Details and the cause of crash can also be viewed in the statistics page on AppGallery Connect.
How to access to the Crash Service Page:
Navigate to Quality > Crash. The Crash page is displayed.
Tips & Tricks
1. Download latest HMS Flutter plugin.
2. Do not forget to create sandbox account.
3. Do not forget to click pug get after adding dependencies.
4. Latest HMS Core APK is required.
Conclusion
In this article, we have learnt integration of Huawei Iap kit, Crash service into Flutter project.
Thanks for reading! If you enjoyed this story, please click the Like button and Follow. Feel free to leave a Comment below.
Reference
In-App Purchase Kit URL
Crash service URL
Original Source
View attachment 5589007
Introduction
In this article, I will be integrating Huawei Account Kit in an Application. Account Kit provides you with simple, secure and quick sign-in and authorization functions. By integrating the Auth Service SDK into our app, we can easily and quickly provide functions such as registration and sign-in for our users. We can choose to provide our users with one or more of the authentication modes like Mobile number, Email address, Facebook, WeChat etc. We will integrate the mobile number authentication mode into the app, so that our users can use mobile numbers and passwords or verification codes to sign in to the app securely.
React Native
React Native helps you to create real and exciting mobile apps with the help of JavaScript only, which is supportable for both android and iOS platforms.
Just code once, and the React Native apps are available for both iOS and Android platforms which helps to save development time.
React Native is a framework that builds a hierarchy of UI components to build the JavaScript code.
It uses the same fundamental UI building blocks as regular iOS and Android apps.
Requirements
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.2.300 or later.
3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
4. Minimum API Level 21 is required.
5. Required EMUI 9.0.0 and later version devices.
Integrate HMS Dependencies
1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
2. Create a project in android studio, refer Creating an Android Studio Project.
3. Generate a SHA-256 certificate fingerprint.
4. To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
Or use cmd as explained in SHA256 CODE
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.
View attachment 5589009
7. Enter SHA-256 certificate fingerprint and click Save, as follows.
View attachment 5589013
8. Click Manage APIs tab and enable Account Kit.
React Native Project Preparation
9. Environment set up, refer below link.
Setting up the development environment · React Native
This page will help you install and build your first React Native app.
reactnative.dev
10. Create project using below command.
react-native init project name
11. Download the React Native Account Kit SDK and paste it under Node Modules directory of React Native project. If you cannot find node modules run below command under project directory using CLI.
“npm install” & “npm link”
12. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
13. Configure app level build.gradle. (Add to dependencies)
Code:
Implementation project (“:react-native-hms-account”)
14. Linking the HMS Account Kit Sdk.
Run below command in the project directory
Code:
react-native link react-native-hms-account
15. Add below permissions to Android.manifest file.
XML:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
16. Enabling Auth Service
(i). Sign in to AppGallery Connect and click My projects.
(ii). Click a project that you want to enable Auth Service from the project list.
(iii). Choose Build > Auth Service. If it is the first time that you use Auth Service, click Enable now in the upper right corner.
View attachment 5589017
(iv). Click Enable in the row of each authentication mode to be enabled.
View attachment 5589019
For more details visit this documentation.
Development
Registering an Account
Apply for a verification code for mobile number-based registration. The verification code will be sent to the user's mobile number to ensure that the mobile number belongs to this user. Call PhoneAuthProvider.requestVerifyCode to apply for a registration verification code.
JavaScript:
let settings = new VerifyCodeSettings(
VerifyCodeAction.REGISTER_OR_LOGIN,
"zh_CN",
30
);
PhoneAuthProvider.requestVerifyCode("countryCode", "phoneNumber", settings)
.then((verifyCodeResult) => {
// verifyCodeResult.shortestInterval
// verifyCodeResult.validityPeriod
})
.catch((error) => {
// error
});
Register a user using a mobile number.
Call AGCAuth.createPhoneUser to register a user. After the registration is successful, the user signs in automatically, and you do not need to call the sign-in API again. The password is optional, and the user can sign in using a verification code.
JavaScript:
AGCAuth.getInstance()
.createPhoneUser(
"countryCode",
"phoneNumber",
"password if you want",
"verifyCode"
)
.then((signInResult) => {
// signInResult.user
})
.catch((error) => {
// error
});
After successful sign-in, call AGCAuth.currentUser to obtain user account data.
JavaScript:
AGCAuth.getInstance()
.currentUser()
.then((user) => {
if (user) {
// A user signed in
}
});
Signing In with a Password
On the app sign-in page, obtain user information from AppGallery Connect, and check whether a user has signed in. If a user has signed in, the user's home page is displayed; if no user has signed in, the sign-in page is displayed.
JavaScript:
AGCAuth.getInstance()
.currentUser()
.then((user) => {
if (user) {
// A user signed in
}
});
Call AGCAuth.signIn for sign-in.
JavaScript:
let credential = PhoneAuthProvider.credentialWithPassword(
"countryCode",
"phoneNumber",
"password"
);
AGCAuth.getInstance()
.signIn(credential)
.then((signInResult) => {
if (signInResult && signInResult.user) {
// signInResult.user get user info
}
})
.catch((error) => {
// error
});
After successful sign-in, call AGCAuth.currentUser to obtain user account data.
Signing In with a Verification Code
On the app sign-in page, obtain user information from AppGallery Connect, and check whether a user has signed in. If a user has signed in, the user's home page is displayed; if no user has signed in, the sign-in page is displayed.
JavaScript:
AGCAuth.getInstance()
.currentUser()
.then((user) => {
if (user) {
// A user signed in
}
});
Call PhoneAuthProvider.requestVerifyCode to apply for a verification code.
JavaScript:
let settings = new VerifyCodeSettings(
VerifyCodeAction.REGISTER_OR_LOGIN,
"zh_CN",
30
);
PhoneAuthProvider.requestVerifyCode("countryCode", "phoneNumber", settings)
.then((verifyCodeResult) => {
// verifyCodeResult.shortestInterval
// verifyCodeResult.validityPeriod
})
.catch((error) => {
// error
});
Call AGCAuth.signIn for sign-in.
JavaScript:
let credential = PhoneAuthProvider.credentialWithVerifyCode(
"countryCode",
"phoneNumber",
null,
"verificationCode"
);
AGCAuth.getInstance()
.signIn(credential)
.then((signInResult) => {
if (signInResult && signInResult.user) {
// signInResult.user get user info
}
})
.catch((error) => {
// error
});
After successful sign-in, call AGCAuth.currentUser to obtain user account data.
Testing
Run the android App using the below command.
Code:
react-native run-android
Result
{
"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"
}
Conclusion
In this article, we have learnt that how to integrate the mobile number authentication mode into the app, so that our users can use mobile numbers and passwords or verification codes to sign in to the app securely.
Reference
Account Kit: Documentation
Account Kit: Training Video