Implementing SMS Verification with Huawei SMS Retriever - EMUI Bugs and Issues

Hi everyone! Today I will briefly walkthrough you about how to implement an SMS Retriever system using Huawei’s SMSRetriever service.
{
"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"
}
First of all, let’s start with why do we need this service in our apps. Applications that involve user verification usually do this with an SMS code, and this SMS code is entered to a field in the app to verify user account. These sms codes are named as One-Time-Password, OTP for short. OTP’s can be used for verification of real user or increasing account security. Our purpose here is to retrieve this code and automatically enter it to the necessary field in our app. So let’s begin!
Our steps through the guide will be as:
Complete HMS Service implementation
1 — Require SMS read permission
2 — Initiate ReadSmsManager
3 — Register broadcast receiver for SMS
4 — Send SMS for user
5 — Register broadcast receiver for OTP — to extract code from SMS —
6 — Create SMSBroadcastReceiver class
1 — We begin by adding our required permission to the AndroidManifest.xml
XML:
<uses-permission android:name="android.permission.SEND_SMS" />
Note: Don’t forget to check if user has given permission.
Code:
val permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
if (permissionCheck == PackageManager.PERMISSION_GRANTED)
// Send sms
else
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.SEND_SMS), SEND_SMS_REQUEST_CODE)
2 — Then we add the ReadSmsManager to initiate our SMS service.
Before ReadSmsManager code snippet, we have to add Huawei Account Kit implementation.
Code:
implementation 'com.huawei.hms:hwid:5.1.0.301'
After Gradle sync, we can add the SMS manager to our class.
Code:
val task = ReadSmsManager.startConsent([email protected], mobileNumber)
task.addOnCompleteListener {
if (task.isSuccessful) {
Toast.makeText(this, "Verification code sent successfully", Toast.LENGTH_LONG).show()
} else
Toast.makeText(this, "Task failed.", Toast.LENGTH_LONG).show()
}
3 — For SMS broadcast receiver, we need to add this little code block.
Code:
val intentFilter = IntentFilter(READ_SMS_BROADCAST_ACTION)
registerReceiver(SmsBroadcastReceiver(), intentFilter)
Note: After you add this code block, you will get an error saying SmsBroadcastReceiver cannot be found, because we didn’t define it yet. We are just getting our SmsActivity ready. We will be adding it once we are done here.
4 — After we register our receiver, we can send the SMS to our user.
Code:
val smsManager = SmsManager.getDefault()
smsManager.sendTextMessage(
mobileNumber,
null,
"Your verification code is $otp",
null,
null
)
Note: here otp will cause an error as it is not defined anywhere yet. You should implement a random OTP generator fitting your likings and assign the value to otp .
5 — Now that we sent an SMS to user, we should register the broadcast receiver to be able to retrieve the code from it.
Code:
val filter = IntentFilter()
filter.addAction("service.to.activity.transfer")
val otpReceiver = object : BroadcastReceiver() {
override fun onReceive(
context: Context,
intent: Intent
) {
intent.getStringExtra("sms")?.let { data ->
// You should find your otp code here in `data`
}
}
}
registerReceiver(otpReceiver, filter)
Note: Once we complete our classes, you should be setting your otp value to your view. This part is left out in the code snippet as view bindings and data bindings may vary on projects.
6 —Finally, where we get to read the messages and find our code.
Code:
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.huawei.hms.common.api.CommonStatusCodes
import com.huawei.hms.support.api.client.Status
import com.huawei.hms.support.sms.common.ReadSmsConstant
class SmsBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val bundle = intent!!.extras
if (bundle != null) {
val status: Status? = bundle.getParcelable(ReadSmsConstant.EXTRA_STATUS)
if (status?.statusCode == CommonStatusCodes.TIMEOUT) {
// Process system timeout
} else if (status?.statusCode == CommonStatusCodes.SUCCESS) {
if (bundle.containsKey(ReadSmsConstant.EXTRA_SMS_MESSAGE)) {
bundle.getString(ReadSmsConstant.EXTRA_SMS_MESSAGE)?.let {
val local = Intent()
local.action = "service.to.activity.transfer"
local.putExtra("sms", it)
context!!.sendBroadcast(local)
}
}
}
}
}
}
So that’s it. You should be able to successfully register for SMS sending and retrieving, then read OTP from content and use in whatever way you like.
Thanks for reading through the guide and I hope it is simple and useful for you. Let me know if you have any suggestions or problems.
References
https://developer.huawei.com/consum...upport-sms-readsmsmanager-0000001050050553-V5
https://developer.huawei.com/consum...Guides/authotize-to-read-sms-0000001061481826
https://medium.com/huawei-developers/android-integrating-your-apps-with-huawei-hms-core-1f1e2a090e98

Related

How to quickly add Sign In with Email to your Android App

Certain kind of apps require user registration to provide relevant information or save user's generated content/preferences in a server. If you are building an app with this feature, you may be interested in Huawei Auth Service to quickly develop your Log In screen with support of the most popular Third-party accounts. I've talked about how to set up the Auth Service in a previous post, so now will show you how to add the Sign In with Email to your Huawei Auth Service implementation.
Previous requirements
A developer account
An app project on AGC with Auth Service integrated
Note: Auth service requires a Data Storage Location, be careful when selecting this, because your app will be only available to certain countries per location.
Enabling the service
You must enable the account types to be supported by Auth Service one by one. Enable the Email support by going to AGC > My projects > "Your Project" > Auth Service.
{
"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"
}
Auth Service configurtion panel
Layout
Add a button and an EditText to your Login screen to get the user's email.
Layout editor
Adding the logic
Add the onClickListener to your login button
Code:
mailBtn.setOnClickListener(this)
override fun onClick(v: View?) {
loadingDialog.show()
when (v?.id) {
R.id.hw -> signInWithHWID()
R.id.google_sign_in_button -> signInWithGoogle()
R.id.anon -> signInAnonymously()
R.id.mailBtn -> signInWithMail()
}
}
I suggest you using a regular expression to check if the given email has a proper format. If everything is ok, you can send a verification code to the email address
Code:
private fun signInWithMail() {
val input = mail.text.toString()
val regex = Regex("^[\\w-\\.][email protected]([\\w-]+\\.)+[\\w-]{2,4}\$")
if (!regex.matches(input)) {
Snackbar.make(mailBtn, "Please use a valid email", Snackbar.LENGTH_SHORT).show()
return
}
val settings = VerifyCodeSettings.newBuilder()
.action(ACTION_REGISTER_LOGIN) //ACTION_REGISTER_LOGIN/ACTION_RESET_PASSWORD
.sendInterval(30) // Minimum sending interval, ranging from 30s to 120s.
.build()
val task: Task<VerifyCodeResult> = EmailAuthProvider.requestVerifyCode(
input,
settings
)
task.addOnSuccessListener {
//The verification code application is successful.
Snackbar.make(
mailBtn,
"Verification code sent to your mailbox",
Snackbar.LENGTH_SHORT
).show()
Log.e("EmailAuth", "success")
//Display dialog
val dialog = VerifyDialog(this, input)
dialog.listener = this
dialog.show()
}
.addOnFailureListener {
Log.e("EmailAuth", it.toString())
}
}
In my case, I've chosen to show a dialog, waiting for the verification code.
Dialog layout
Then the dialog will report the given code and password to the Fragment / Activity
Code:
class VerifyDialog(val context: Context,val email: String):DialogInterface.OnClickListener{
lateinit var view:View
var listener:VerificationListener?=null
var alertDialog: AlertDialog
init{
val inflater=LayoutInflater.from(context)
view=inflater.inflate(R.layout.dialog_verify,null)
val builder=AlertDialog.Builder(context)
builder.setTitle("Email Verification")
.setView(view)
.setPositiveButton("ok",this)
.setNegativeButton("Cancel",this)
.setCancelable(false)
alertDialog=builder.create()
}
public fun show(){
alertDialog.show()
}
override fun onClick(dialog: DialogInterface?, which: Int) {
when(which){
DialogInterface.BUTTON_POSITIVE ->{
val code=view.inputCode.text.toString()
if(code==""){
Snackbar.make(view,"Please input the code",Snackbar.LENGTH_SHORT).show()
return
}
val pass=view.inputPass.text.toString()
val vPass=view.confirmPass.text.toString()
if(pass.isEmpty()||pass!=vPass){
Snackbar.make(view,"Passwords doesn't match",Snackbar.LENGTH_SHORT).show()
return
}
listener?.onVerification(code,email,pass)
}
DialogInterface.BUTTON_NEGATIVE ->{
dialog?.dismiss()
listener?.onCancel()
}
}
}
public interface VerificationListener{
fun onVerification(code:String,email:String,password:String)
fun onCancel()
}
}
Report the code and password to AGC, so the user can use the password to sign in the next time.
Note: Setting the password is not mandatory.
Code:
override fun onVerification(code: String, email: String, password: String) {
val emailUser = EmailUser.Builder()
.setEmail(email)
.setVerifyCode(code)
.setPassword(password) // Optional. If this parameter is set, the current user has created a password and can use the password to sign in.
// If this parameter is not set, the user can only sign in using a verification code.
.build()
AGConnectAuth.getInstance().createUser(emailUser)
.addOnSuccessListener {
// After an account is created, the user is signed in by default.
startNavDrawer(it.user)
}
.addOnFailureListener {
Log.e("AuthSevice","Email Sign In failed $it")
}
}
Conclusion
Now your users can Sign In with their email adress. You can check the full example here: DummyApp
Reference
Official document:https://developer.huawei.com/consum...-connect-Guides/agc-auth-service-introduction
Hi am trying to implement email login but am getting email null do we need to anything.
Hi Is there any ways to use Huawei Auth Service as one like firebase UI ?

Sending SMS with Huawei Scan Kit

​
Sending SMS with Huawei Scan Kit​
{
"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"
}
​This article is about sending sms with the Huawei scan kit.
Huawei Scan Kit Integration
Configure app information in AppGallery Connect
Integrate the HMS Core SDK
Assign permissions
Sending SMS with Huawei Scan Kit
Add Required Permissions for Barcode Scanning and sms sending to AndroidManifest.xml
Code:
<!--Camera permission-->
<uses-permission android:name="android.permission.CAMERA"/>
<!--Sms permission-->
<uses-permission android:name="android.permission.SEND_SMS" />
Dynamically request the permissions in the MainActivity.java file
Code:
private fun requestPermission(requestCode: Int) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.CAMERA, Manifest.permission.SEND_SMS),
requestCode)
}
Code:
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray){
if (grantResults.size < 2 || permissions == null || grantResults == null || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "missing permission", Toast.LENGTH_LONG).show()
return
}
if (requestCode == REQUEST_SMS) {
val options = HmsScanAnalyzerOptions
.Creator()
.setHmsScanTypes(HmsScan.SMS_FORM, HmsScan.DATAMATRIX_SCAN_TYPE)
.create()
ScanUtil.startScan(this,
REQUEST_CODE_SMS , options)
}
}
You can use the link for more detail about required permissions.
In line 12, scan process starts. HmsScanType value must set SMS_FORM for sending sms.
Sample barcode value is as follows.
Original value : smsto:18300000000 : Hello World!
Mobile number of an SMS message : 18300000000
SMS message content : Hello World!
Data need to be parsed in onActivityResult to get mobile number and message content.
Code:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (data != null) {
when(resultCode){
Activity.RESULT_OK ->{
if(requestCode == REQUEST_CODE_SMS) {
val result : HmsScan? = data.getParcelableExtra(ScanUtil.RESULT)
val sms = result?.let { getMessage(it) }
sms?.let { sendMessage(it) }
}
}
}
}
}
Code:
private fun getMessage(result : HmsScan): HmsScan.SmsContent? {
return when(result?.smsContent == null) {
true -> null
false -> {
result.smsContent
}
}
}
You can use URI schemes for composing and sending messages.
Code:
private fun sendMessage (smsInfo: HmsScan.SmsContent) {
if(smsInfo == null){
Toast.makeText(this, "sms information could not found", Toast.LENGTH_LONG).show()
return
}
if(smsInfo.getDestPhoneNumber().isBlank() || smsInfo.getMsgContent().isBlank()) {
Toast.makeText(this, "incorrect phone number or message content", Toast.LENGTH_LONG).show()
return
}
val intent = Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", smsInfo.destPhoneNumber, null))
intent.putExtra("sms_body", smsInfo.msgContent)
startActivity(intent)
}
Create an message intent with the sms content and mobile number obtained from the barcode. The correct scheme is “sms” for messaging.
Use Cases
Contact potential customers : You can add a QR code to the your card with the note “Scan this to contact us”. When the QR code is scaned, a pre-written message “I want to get information about your product” may appear.
Subscribe or purchase digital products : You can add a QR code to your web site so that the your product can be purchased using the QR code. When the QR code is scanned, a message that says “I want to buy discount coupon or subscribe your channel” may appear.
Conclusion
I hope this article helps you better understand the Huawei scan kit and its use cases.
Thanks for reading. If you have question, don’t hesitate to contact me.
References:​
Scan Kit - Code Scanning Service - HUAWEI Developer
Scan Kit scans and parses all major 1D and 2D barcodes and generates QR codes, helping you quickly build barcode scanning functions into your apps.
developer.huawei.com
List of URI schemes - Wikipedia
en.wikipedia.org
https://github.com/HMS-Core/hms-scan-demo
What is the benefit of this over sending message through device Message app?
ask011 said:
What is the benefit of this over sending message through device Message app?
Click to expand...
Click to collapse
For same operation, message can be sent through device message app or the code can be scaned to automatically open local SMS app and pre-fill the number and message fields.
Since the second method is faster, it is a preferred method today as an SMS marketing strategy.

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

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

Integrating Auth Service into a Xamarin Android App

Xamarin (Microsoft) is a multi-system development platform for mobile services that many developers use. Many AppGallery Connect services now support Xamarin, including Auth Service. Here I’ll explain on how to integrate Auth Service into your Xamarin.Android app that requires mobile number sign-in support.
Install the Xamarin environment.​You’ll need to first download and install Visual Studio 2019.
Open Visual Studio and select Mobile development with .NET to install the Xamarin environment.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Next make sure you have enabled the Auth Service in AppGallery Connect.
Open Visual Studio, click Create a new project in the start window, select Mobile App (Xamarin.Forms), and set the app name and other required information.
Right-click your project and choose Manage NuGet Packages.
Search for the Huawei.Agconnect.Auth package on the displayed page and install it.
Download the JSON service file from your AppGallery project and add it into the *Assets directory in your project.
Create a new class named HmsLazyInputStreams.cs, and implement the following code to read the JSON file.
Code:
using System;
using System.IO;
using Android.Util;
using Android.Content;
using Huawei.Agconnect.Config;
namespace XamarinAuthDemo
{
class HmsLazyInputStream : LazyInputStream
{
public HmsLazyInputStream(Context context) : base(context)
{
Get(context);
}
public override Stream Get(Context context)
{
try
{
return context.Assets.Open("agconnect-services.json");
}
catch (Exception e)
{
Log.Error(e.ToString(), "Failed to get input stream" + e.Message");
return null;
}
}
}
}
Then add the following code to AttachBaseContext under MainActivity.
Code:
protected override void AttachBaseContext(Context context){
base.AttachBaseContext(context);
AGConnectServicesConfig config = AGConnectServicesConfig.FromContext(context);
config.OverlayWith(new HmsLazyInputStream(context));
}
Right-click your project and choose Properties. Click Android Manifest on the displayed page, and set a package name.
Once you’ve completed all of these preparations, you’ll be able to develop app functions.
If your app requires mobile number sign-in support, the Auth Service SDK can help you implement both sign-up and sign-in for this authentication mode. You’ll need to send verification codes to your users for both stages. Auth Service can help you with that as well.
Setup Mobile Number verification​Create a VerifyCodeSettings object that contains the SMS messaging settings, including the action and language.
Code:
VerifyCodeSettings settings = VerifyCodeSettings.NewBuilder()
.Action(VerifyCodeSettings.ActionRegisterLogin)
.SendInterval(30)
.Locale(Locale.English)
.Build();
Call the RequestVerifyCodeAsync method to send a request to the Auth Service server, and pass the country code and mobile number entered by a user, and the VerifyCodeSettings object you just created, for Auth Service to send a verification code SMS message to the user.
Code:
string countryCode = edtCountryCode.Text.ToString().Trim();
string phoneNumber = edtAccount.Text.ToString().Trim();
try {
var requestVerifyCode = AGConnectAuth.Instance.RequestVerifyCodeAsync(countryCode, phoneNumber, settings);
VerifyCodeResult verifyCodeResult = await requestVerifyCode;
if(requestVerifyCode.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion)) {
Toast.MakeText(this, "The verification code is sent successfully! ", ToastLength.Short).Show();
}
} catch (Exception ex) {
Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
}
Upon receiving the verification code, the user can start sign-up.
First, you’ll need to create a PhoneUser object to store the user’s inputs, including the mobile number, country code, verification code, and password. The user can choose whether to set a password. If so, they’ll need to enter a password when signing in to your app.
Code:
string countryCode = edtCountryCode.Text.ToString().Trim();
string phoneNumber = edtAccount.Text.ToString().Trim();
string password = edtPassword.Text.ToString().Trim();
string verifyCode = edtVerifyCode.Text.ToString().Trim();
// Create a PhoneUser object.
PhoneUser phoneUser = new PhoneUser.Builder()
.SetCountryCode(countryCode)
.SetPhoneNumber(phoneNumber)
.SetPassword(password)
.SetVerifyCode(verifyCode)
.Build();
Call the CreateUserAsync method to create a user.
Code:
try {
// Create a mobile number user.
var phoneUserResult = AGConnectAuth.Instance.CreateUserAsync(phoneUser);
ISignInResult signInResult = await phoneUserResult;
if (phoneUserResult.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion)) {
// After the user is created, they are automatically signed in to your app.
StartActivity(new Intent(this, typeof(MainActivity)));
}
} catch (Exception ex) {
Toast.MakeText(this, "Create User Fail:" + ex.Message, ToastLength.Long).Show();
}
Once sign-up is complete, the Auth Service SDK will automatically sign the user in to your app, and you won’t need to call the sign-in API again.
For an existing user, you need to implement the sign-in process, either via a verification code or a password.
Code:
string countryCode = edtCountryCode.Text.ToString().Trim();
string phoneNumber = edtAccount.Text.ToString().Trim();
string password = edtPassword.Text.ToString().Trim();
string verifyCode = edtVerifyCode.Text.ToString().Trim();
IAGConnectAuthCredential credential;
if (TextUtils.IsEmpty(verifyCode)) {
credential = PhoneAuthProvider.CredentialWithPassword(countryCode, phoneNumber, password);
} else {
credential = PhoneAuthProvider.CredentialWithVerifyCode(countryCode, phoneNumber, password, verifyCode);
}
try {
AGConnectAuth connectAuth = AGConnectAuth.Instance;
var signInResult = AGConnectAuth.Instance.SignInAsync(credential);
ISignInResult result = await signInResult;
if (signInResult.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion)) {
Log.Debug(TAG, signInResult.Result.ToString());
StartActivity(new Intent(this, typeof(MainActivity)));
Finish();
}
} catch (Exception ex) {
Log.Error(TAG, ex.Message);
Toast.MakeText(this, "SignIn failed: " + ex.Message, ToastLength.Long).Show();
}
You can call CredentialwithPassword or CredentialWithVerifyCode to generate a credential for a password sign-in or a verification code sign-in, respectively. Then call the SignInAsync method to pass the credential for sign-in.
And thats it! We now have a fully functional authentication system using the users mobile number to confirm they are who they say they are.
Xamarin is a free tool or paid?​

Implement Huawei AppGallery Auth Service in your Xamarin Android app with Facebook Login support

Xamarin (Microsoft) is a multi-system development platform for mobile services that many developers use. Many AppGallery Connect services now support Xamarin, including Auth Service. Here I’ll explain on how to integrate Auth Service into your Xamarin.Android app and use the 3rd party auth support for Facebook.
Install the Xamarin environment and project setup.​You’ll need to first download and install Visual Studio 2019.
Open Visual Studio and select Mobile development with .NET to install the Xamarin environment.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Next make sure you have enabled the Auth Service in AppGallery Connect.
Open Visual Studio, click Create a new project in the start window, select Mobile App (Xamarin.Forms), and set the app name and other required information.
Right-click your project and choose Manage NuGet Packages.
Search for the Huawei.Agconnect.Auth package on the displayed page and install it.
Download the JSON service file from your AppGallery project and add it into the *Assets directory in your project.
Create a new class named HmsLazyInputStreams.cs, and implement the following code to read the JSON file.
Code:
using System;
using System.IO;
using Android.Content;
using Android.Util;
using Huawei.Agconnect.Config;
namespace AppLinking1
{
public class HmsLazyInputStream : LazyInputStream
{
public HmsLazyInputStream(Context context)
: base(context)
{
}
public override Stream Get(Context context)
{
try
{
return context.Assets.Open("agconnect-services.json");
}
catch (Exception e)
{
Log.Error("Hms", $"Failed to get input stream" + e.Message);
return null;
}
}
}
}
Right-click your project and choose Properties. Click Android Manifest on the displayed page and set a package name
Follow the process that Facebook describes to setup your application with their platform. Details can be found here
Finally the last thing we need to do is install the Xamarin Facebook login package.
Right-click your project and choose Manage NuGet Packages. Search for Xamarin.Facebook.Login.Android and install it.
Implement Facebook Auth​Create a login button within your application, this will use the below code to start the login process getting the specific requested account details from Facebook and process this using the call back.
Code:
private void ImgFacebook_Click(object sender, EventArgs e){
callBackManager = CallbackManagerFactory.Create();
ICollection<string> collection = new List<string>();
collection.Add("public_profile");
collection.Add("user_friends");
LoginManager.Instance.LogInWithReadPermissions(this, collection);
LoginManager.Instance.RegisterCallback(callBackManager, new FacebookCallback(this));
}
The Facebook Callback then looks like:
Code:
private class FacebookCallback : Java.Lang.Object, IFacebookCallback {
LoginActivity loginActivity;
public FacebookCallback(LoginActivity loginActivity) {
this.loginActivity = loginActivity;
}
public void OnCancel() {
Log.Debug("IFacebookCallback", "Cancelled.");
}
public void OnError(FacebookException error) {
Log.Error("IFacebookCallback", "Failed: " + error.Message);
}
public void OnSuccess(Java.Lang.Object result) {
LoginResult loginResult = (LoginResult)result;
Log.Debug("IFacebookCallback", "Facebook login successfuly. Access token: " + loginResult.AccessToken.Token);
IAGConnectAuthCredential credential = FacebookAuthProvider.CredentialWithToken(loginResult.AccessToken.Token);
try {
AGConnectAuth connectAuth = AGConnectAuth.Instance;
var signInResult = AGConnectAuth.Instance.SignInAsync(credential);
ISignInResult result = await signInResult;
if (signInResult.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion)){
Log.Debug(TAG, signInResult.Result.ToString());
StartActivity(new Intent(this, typeof(MainActivity)));
Finish();
}
} catch (Exception ex) {
Log.Error(TAG, ex.Message);
Toast.MakeText(this, "SignIn failed: " + ex.Message, ToastLength.Long).Show();
}
}
}
In the OnSuccess method, we have obtained the access token and generated a credential for Facebook Login, and called SignInAsync to pass the credential for sign-in.
Finally, forward OnActivityResult to the callBackManager.
Code:
if (requestCode == 64206){
callBackManager.OnActivityResult(requestCode, (int)resultCode, data);
}
The result code 64206 is defined by Facebook in its Login SDK. It is used to identify the callback for Facebook Login when there are multiple callbacks in OnActivityResult. An interesting fact is that, the hexadecimal value of 64206 is 0xFACE, which is a little trick from Facebook.

Categories

Resources