Sending SMS with Huawei Scan Kit - Huawei Developers

​
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.

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 ?

Implementing SMS Verification with Huawei SMS Retriever

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

Connecting to Wifi with Huawei Scan Kit

Connecting to Wifi 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 connecting to the wireless network with the Huawei scan kit.
Huawei Scan Kit Integration
Configure app information in AppGallery Connect
Integrate the HMS Core SDK
Assign permissions
Connecting to Wifi with Huawei Scan Kit
Code:
<!--Camera permission-->
<uses-permission android:name="android.permission.CAMERA" />
<!--Network permission-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Dynamically request the permissions in the MainActivity.java file
Code:
private fun requestPermission(requestCode: Int) {
ActivityCompat.requestPermissions (
this,
arrayOf(Manifest.permission.CAMERA, Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.CHANGE_NETWORK_STATE),
requestCode)
}
Code:
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray){
if (grantResults.size < 5 || permissions == null || grantResults == null || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "missing permission", Toast.LENGTH_LONG).show()
return
}
if (requestCode == REQUEST_WIFI) {
val options = HmsScanAnalyzerOptions
.Creator()
.setHmsScanTypes(HmsScan.WIFI_CONNECT_INFO_FORM, HmsScan.DATAMATRIX_SCAN_TYPE)
.create()
ScanUtil.startScan(this,
REQUEST_CODE_WIFI_INFORMATION, options)
}
}
You can use the link for more detail about required permissions.
In line 12, scan process starts. HmsScanType value must set WIFI_CONNECT_INFO_FORM for getting information of wifi.
HmsScan.WiFiConnectionInfo
Sample barcode value is as follows.
Original value : WIFI:S:WIFI_123;T:WPA;P:12345678;;
Wi-Fi SSID : WIFI_123
Wi-Fi Password : 12345678
Wi-Fi encryption type : WPA
Data need to be parsed in onActivityResult to get password and ssid.
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_WIFI_INFORMATION) {
val result : HmsScan? = data.getParcelableExtra(ScanUtil.RESULT)
val wifiConnectionInfo = result?.let { getWifiInformation(it) }
wifiConnectionInfo?.let { connectToWifi(it) }
}
}
}
}
}
Code:
private fun getWifiInformation(result : HmsScan): HmsScan.WiFiConnectionInfo? {
return when(null == result || null == result.wiFiConnectionInfo == null) {
true -> null
false -> {
result.wiFiConnectionInfo
}
}
}
You can use the android.net library to connect to wifi using the password and ssid.
Code:
private fun connectToWifi(wifiConnectionInfo : HmsScan.WiFiConnectionInfo) {
if(wifiConnectionInfo == null){
Toast.makeText(this, "wifi information could not found", Toast.LENGTH_LONG).show()
return
}
if(wifiConnectionInfo.password.isBlank() || wifiConnectionInfo.password.isBlank()) {
Toast.makeText(this, "incorrect password or connection name", Toast.LENGTH_LONG).show()
return
}
val connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val wifiNetworkSpecifier = createWifiNetworkSpecifier(wifiConnectionInfo)
val networkRequest = createNetworkRequest(wifiNetworkSpecifier)
val networkCallback = createNetworkCallback()
networkRequest?.let { connectivityManager.requestNetwork(it, networkCallback) }
}
The first step is to create a WifiNetworkSpecifier with the ssid and password obtained from the barcode.
Code:
private fun createWifiNetworkSpecifier(wifiConnectionInfo: HmsScan.WiFiConnectionInfo): WifiNetworkSpecifier {
return WifiNetworkSpecifier
.Builder()
.setSsid(wifiConnectionInfo.ssidNumber)
.setWpa2Passphrase(wifiConnectionInfo.password)
.build()
}
The second step is to create a NetworkRequest with the wifiNetworkSpecifier created in the previous step.
Code:
private fun createNetworkRequest(wifiNetworkSpecifier : WifiNetworkSpecifier): NetworkRequest? {
return NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(wifiNetworkSpecifier)
.build()
}
NetworkCallback is base class for NetworkRequest. Used for notifications about network changes. Should be extended by applications wanting notifications.
Code:
private fun createNetworkCallback(): ConnectivityManager.NetworkCallback {
return object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
Log.i("ConnectToNetwork", "network is available")
}
override fun onUnavailable() {
Log.e("ConnectToNetwork", "network is unavailable")
}
}
}
If a network matching the ssid is found, the connect to wireless network option will be shown. After clicking connect button, If the password is correct, it will be successfully connected to the network.
Following alert will be shown, if a network matching the ssid cannot be found.
Use Cases
Sharing wifi with customers in the cafe and restaurant.
Sharing wifi with passengers in public transportation
Conclusion
I hope this article helps you better understand the usage scenarios of the Huawei scanning kit.
Thanks for reading. If you have question, don’t hesitate to contact me.
References:​https://github.com/HMS-Core/hms-scan-demo
https://developer.android.com/reference/android/net/package-summary
developer.huawei.com
Click to expand...
Click to collapse
Its very interesting, Thanks for sharing.
sujith.e said:
Its very interesting, Thanks for sharing
Click to expand...
Click to collapse
thanks for your feedback, wish you pleasant reading
can we share files as well?
shikkerimath said:
can we share files as well?
Click to expand...
Click to collapse
codes of the project?
Which API is used for discovering the WIFI device?
does it support wifi direct?
ask011 said:
Which API is used for discovering the WIFI device?
Click to expand...
Click to collapse
android.net library is used at the project.
android.net | Android Developers
developer.android.com
ProManojKumar said:
does it support wifi direct?
Click to expand...
Click to collapse
Scan Kit supports extracting wifi information and returns the information to you but doesn't support discovering wifi direct. Android.net library can be used for it.
Does it detect passwords as well?
if Qr code contains passwords
Basavaraj.navi said:
Does it detect passwords as well?
Click to expand...
Click to collapse
If the QR code contains the password of wifi, the password is detected by the app. Otherwise, the password cannot be detected.

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.

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