Search

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Tuesday, July 2, 2019

Xamarin Forms: How to Read SMS and verify OTP automatically in android without using SMS read permission


Introduction:
Google is considering the users privacy seriously, it has updated its Google Play Developer Policy which restricting SMS, CALL_LOG access. If your app does not require access to Call Log or SMS permissions, you must remove the permissions from your app's manifest.
For apps requesting access to the SMS or Call Log permissions, the intended and permitted uses include default SMS handling, default phone handling, or Assistant handling capability, you should only access Call Log or SMS permissions when your app falls within permitted uses and only to enable your app’s critical core functionality.
Android App Should read the SMS some specific needs like verify OTP, The Google Play Services has enabled Android SMS Retriever API allows you to access the SMS Messages and verify it via SMS without device permissions. 
Verification Message Format:
You need to follow as per Google Policy for construct the verification message and send to the user device, the message should be following format.
  • Be no longer than 140 bytes
  • Begin with the prefix <#>
  • One-time Verification code
  • Special 11-character hash for you app. That Hash can be generated by the Application. (will explain following steps)
Now we have very good understanding about Google new policy and message format. This article, I will explain the following steps, it will help you to integrate Android OTP verification code auto read using Xamarin Forms.
  • Create New Xamarin Forms Application.
  • Add Google Play Services Auth
  • Create UI Design 
  • Dependency Service
  • Messaging Center subscribe 
  • ListenToSms Dependency
  • Broadcast Receiver
  • Generate Application Hash Key Helper
  • Demo Application
Create New Xamarin Forms Application
In order to implement Auto read OTP message, let’s start creating a new Xamarin.Forms project using Visual Studio 2019 or VS mac. When accessing Visual Studio 2019 mac for the first time, you will come across a new interface for opening a creating the projects.

Open Visual Studio Mac >>Create New Project or select open recent application.



The available templates will appear on a mac like below. Select Xamarin.Forms application with different mobile platforms.





Add Google Play Service NuGet Package:
After click on Next Button, The Xamairn Project template will generate and load the solutions into the local system. We need to install Xamarin.GooglePlayServices.Auth nuget package to our Android project for SMS Retriever API.
 Right click on Android Project >> Add Nuget Package >> Select or Search “Xamarin.GooglePlayServices.Auth”>> Install the Latest version of Google play service.


Create UI Design:
Create simple UI Design with one Entry and Button Control using Xaml in Xamarin Forms library.
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:ReadOTPXamarinAndroid" x:Class="ReadOTPXamarinAndroid.MainPage">
   <StackLayout Padding="15" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" BackgroundColor="White">
        <Entry  PlaceholderColor="Black" Placeholder="Enter OTP" x:Name="smSEntry"></Entry>
        <Button Text="Wait for sms"  Clicked="ImageButton_OnClicked"></Button>
    </StackLayout>
</ContentPage>


The Design Look like below 
Dependency Service
DependencyService allows apps to call into platform-specific functionality from shared code. This functionality enables Xamarin.Forms apps to do anything that a native app can do. We need to create a interface design will define how you interact with platform-specific functionality. Here, reading OTP will support only android Platform and IOS will support with Autofill so create DependencyService interface for Listen to sms retriever. Create new class and interface for CommonServices.
using Xamarin.Forms;

namespace ReadOTPXamarinAndroid
{
    public static class CommonServices
    
        public static void ListenToSmsRetriever()
        
            DependencyService.Get<IListenToSmsRetriever>()?.ListenToSmsRetriever();
        
    
    public interface IListenToSmsRetriever
    
        void ListenToSmsRetriever();
    

}


Messaging Center subscribe:
Xamarin.Forms MessagingCenter enables different components to communicate without having to know anything about each other besides a simple Message contract. The MessagingCenter is a static class with Subscribe and Send methods that are used throughout the solution.
Subscribe - Listen for messages with a certain signature and perform some action when they are received. Multiple subscribers can be listening for the same message.
Send - Publish a message for listeners to act upon. If no listeners have subscribed then the message is ignored.
Here, we are creating utility for subscribe message listener, it will help for if any new message recived the device notify to the solutions.
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace ReadOTPXamarinAndroid
{
   public static class Utilities
    
        private static readonly object cc = new object();
        public static void Subscribe<TArgs>(this object subscriber, Events eventSubscribed, Action<TArgs> callBack)
        
            MessagingCenter.Subscribe(subscriber, eventSubscribed.ToString(), new Action<object, TArgs>((e, a) => { callBack(a); }));
        
        public static void Notify<TArgs>(Events eventNotified, TArgs argument)
        
            MessagingCenter.Send(cc, eventNotified.ToString(), argument);
        

    
}
Create Enum for message Event type 
using System;
namespace ReadOTPXamarinAndroid
{
    public enum Events
    
        SmsRecieved,
    
}
Code Behind Design View:
The Code Behind add the Subscribe message listener and if any message receive from message app with specific format, it will get notify and read the meesage and assign the OTP value into the Entry Box.   
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ReadOTPXamarinAndroid
{
    public partial class MainPage : ContentPage
    
        public MainPage()
        
            InitializeComponent();
            this.Subscribe<string>(Events.SmsRecieved, code =>
            
                smSEntry.Text = code;
            });
        
        private void ImageButton_OnClicked(object sender, EventArgs e)
        
            CommonServices.ListenToSmsRetriever();
        
    
}
ListenToSms Dependency:
Let start create dependency to android project ,if you are not added Xamarin.GooglePlayServices.Auth NuGet package, try to add before going to create Instance.
Get an instance of SmsRetrieverClient, used to start listening for a matching SMS message. 


SmsRetrieverClient client = SmsRetriever.GetClient(Application.Context);


Starts SmsRetriever, which waits for ONE matching SMS message until timeout (5 minutes). The matching SMS message will be sent via a Broadcast Intent .
            var task = client.StartSmsRetriever();
Listen for success/failure of the start Task. 
using Java.Lang;
using ReadOTPXamarinAndroid.Droid;
using Application = Android.App.Application;

[assembly: Dependency(typeof(ListenToSms))]

namespace ReadOTPXamarinAndroid.Droid
{
    public class ListenToSms : IListenToSmsRetriever
    
        public void ListenToSmsRetriever()
        
           
            SmsRetrieverClient client = SmsRetriever.GetClient(Application.Context);
            var task = client.StartSmsRetriever();
            task.AddOnSuccessListener(new SuccessListener());
            task.AddOnFailureListener(new FailureListener());
        
        private class SuccessListener : Object, IOnSuccessListener
        
            public void OnSuccess(Object result)
            
            
        
        private class FailureListener : Object, IOnFailureListener
        
            public void OnFailure(Exception e)
            
            
        
    

}
Broadcast Receiver:
The BroadcastReceiver that will be listening to the broadcasts of the above SmsRetreieverClient.SMS Retriever API has provided us with an intent filter SmsRetriever.SmsRetrievedAction which we will use to register our BroadcastReceiver, which we’re going name as SMSBroadcastReceiver, and implement as following.
using System.Linq;
using System.Text.RegularExpressions;
using Android.App;
using Android.Content;
using Android.Gms.Common.Apis;
using Com.Google.Android.Gms.Auth.Api.Phone;
using ReadOTPXamarinAndroid;

namespace ReadOTPXamarinAndroid.Droid
{
    [BroadcastReceiver(Enabled = true, Exported = true)]
    [IntentFilter(new[] { SmsRetriever.SmsRetrievedAction })]
    public class SmsReceiver : BroadcastReceiver
    
        private static readonly string[] OtpMessageBodyKeywordSet = { "DevEnvExe Generated OTP" }; //You must define your own Keywords
        public override void OnReceive(Context context, Intent intent)
        
            try
            

                if (intent.Action != SmsRetriever.SmsRetrievedAction) return;
                var bundle = intent.Extras;
                if (bundle == null) return;
                var status = (Statuses)bundle.Get(SmsRetriever.ExtraStatus);
                switch (status.StatusCode)
                
                    case CommonStatusCodes.Success:
                        var message = (string)bundle.Get(SmsRetriever.ExtraSmsMessage);
                        var foundKeyword = OtpMessageBodyKeywordSet.Any(k => message.Contains(k));
                        if (!foundKeyword) return;
                        var code = ExtractNumber(message);
                        Utilities.Notify(Events.SmsRecieved, code);
                        break;
                    case CommonStatusCodes.Timeout:
                        break;
                

            
            catch (System.Exception)
            
                // ignored
            
        
        private static string ExtractNumber(string text)
        
            if (string.IsNullOrEmpty(text)) return "";
            var number = Regex.Match(text, @"\d+").Value;
            return number;
        
    

}
We have done code for now; it will go for testing. Before going to demo let we re consider the format of SMS, in that we need to get know about Application Hash key, Ley you follow below step for generate application hash key  
Generate Application Hash Key Helper
The hash string is made of your app’s package name and your app’s public key certificate. To generate the hash code, just run the following C# Method to generate hash to be included in your SMS message.
You need to make sure you are generate hash key and append to the OTP message, Without the correct hash, your app won't receive the message callback. 
Hash key will generate once per app and stored. Then you can remove this helper class from your code and create new class into the native android project.

using System;
using System.Linq;
using System.Text;
using Android.Content;
using Android.Content.PM;
using Android.Util;
using Java.Security;
using Java.Util;

namespace ReadOTPXamarinAndroid.Droid.Helper
{
    public class AppHashKeyHelper
    
        private static string HASH_TYPE = "SHA-256";
        private static int NUM_HASHED_BYTES = 9;
        private static int NUM_BASE64_CHAR = 11;

        /// <summary>
        /// Retrieve the app signed package signature
        /// known as signed keystore file hex string
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private static string GetPackageSignature(Context context)
        
            PackageManager packageManager = context.PackageManager;
            var signatures = packageManager.GetPackageInfo(context.PackageName, PackageInfoFlags.Signatures).Signatures;
            return signatures.First().ToCharsString();
        

        /// <summary>
        /// Gets the app hash key.
        /// </summary>
        /// <returns>The app hash key.</returns>
        /// <param name="context">Android app Context.</param>
        public static string GetAppHashKey(Context context)
        
            string keystoreHexSignature = GetPackageSignature(context);

            String appInfo = context.PackageName + " " + keystoreHexSignature;
            try
            
                MessageDigest messageDigest = MessageDigest.GetInstance(HASH_TYPE);
                messageDigest.Update(Encoding.UTF8.GetBytes(appInfo));
                byte[] hashSignature = messageDigest.Digest();

                hashSignature = Arrays.CopyOfRange(hashSignature, 0, NUM_HASHED_BYTES);
                String base64Hash = Android.Util.Base64.EncodeToString(hashSignature, Base64Flags.NoPadding | Base64Flags.NoWrap);
                base64Hash = base64Hash.Substring(0, NUM_BASE64_CHAR);

                return base64Hash;
            
            catch (NoSuchAlgorithmException e)
            
                return null;
            
        
    
}
You can call the GetAppHashkey method into MainActivity and debug the solution and get the hash key value.
Demo and Download Source Code:
The Application Ready now and you can also download the source code from Github , start the application using Android Emulator and click Phone icon from extended controls and add the message as per follow format with hash key. 




Summary
In this article, you learned about Verify OTP Automatically in Android without SMS read permission using Xamarin Forms. I hope this article will help you. Please leave your feedback/query using the comments box, and if you like this article, please share it with your friends.

40 comments:

  1. Usually I do not read post on blogs, but I would like to say that this write-up very forced me to try and do it! Your writing style has been surprised me. Great work admin.Keep update more blog.
    Hire Xamarin Developer

    xamarin developer india

    Hire Xamarin Mobile Developer

    ReplyDelete
  2. Thanks for sharing!!
    Msgclub Bulk sms services offer dedicated long code,shared long code and short code services that is highly used by businesses to receive SMS messages.

    ReplyDelete
  3. Thank you so sharing on bulk sms services. I really appreciate it

    ReplyDelete
  4. Nice Article, You need not draft a design, mock-up content or scale outlines for the ad.Message Sender App is a multiple SMS sending tool from Multiple Android phones through a single platform at once sms sender app

    ReplyDelete
  5. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page! Bulk SMS Nigeria

    ReplyDelete
  6. If more people that write articles really concerned themselves with writing great content like you, more readers would be interested in their writings.Thank you for caring about your content. AmarMobile

    ReplyDelete
  7. Nice Post, Thanks for sharing this quality information with us. You Need To visit this site mobile bd about Mobile phone

    ReplyDelete
  8. Thanks for this information, SMS Marketing is sending promotional campaigns or transactional messages for marketing purposes using text messages (SMS) How to send bulk sms

    ReplyDelete
  9. I agree. In India, currently, government is issuing epass for travel during corona lockdown. e pass delhi can be applied at jantasamvad portal where delhi travel epass coupon application form is provided. The covid-19 epass is important.

    ReplyDelete
  10. Bulk SMS marketing is really the best way to promote business send sms from pc . Bulk sms is very fast tool , sms sender software

    ReplyDelete

  11. So it will be an irritable situation to send SMS to the people individually. They started to think about some tool by which they will be able to send Bulk sms sender software

    ReplyDelete
  12. Very nice article thanks ,This bulk sms sender help you to boost marketing . Bulk sms sender

    ReplyDelete
  13. tiktok name generator
    TikTok Names

    best tiktok names

    aesthetic tiktok names

    tiktok creator name

    bio for tiktok

    tiktok usernames search

    alt tiktok username ideas

    musically name generator
    Loud Updates

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Amazing blog. Bulk sms is very fast tool.Thank you for sharing on bulk sms services.
    mobilevaly

    ReplyDelete
  16. Such a nice article , Sending multiple SMS messages just got a lot easier. sms sender software

    ReplyDelete
  17. I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read!! I definitely really liked every part of it and i also have you saved to fav to look at new information in your site.oppo f15 2020

    ReplyDelete
  18. This is very useful article. I will connect it back to your site though.Phone by price

    ReplyDelete
  19. teatv apk downloadOn this subject internet page, you'll see my best information, be sure to look over this level of detail.

    ReplyDelete
  20. What are The Benefits Of Email Marketing In Digital Era – The world is digitizing at an incredible pace and so do all the marketing channels.  Web email extractor

    ReplyDelete
  21. This is what happened in AppHashKeyHelper.
    The same thing happened in all android's classes :)
    https://s17.picofile.com/file/8420967476/Screenshot_2021_01_11_142341.png

    ReplyDelete
  22. Get the best attractive details on this – The world is digitizing at an incredible pace and so do all the marketing channels.  Web email extractor

    ReplyDelete
  23. Nice article. Thanks for sharing this types of article. I have website for mobile price please visit my site.

    ReplyDelete
  24. Well done your article. In your opinion, we all got to learn something or something. Give us some help wordsera.in
    web
    softiyo

    ReplyDelete
  25. This is very useful article. I will connect it back to your site though. Samsung Mobile Price in Bangladesh

    ReplyDelete
  26. Thanks for share this article. Keep up the good work!! Here Is Daily Latest Updated Mobile Price for Bangladeshi People Who are looking for xiaomi price in bangladesh to buy smartphone.

    ReplyDelete
  27. Sotophone is currently taking the internet by storm due to its highly appropriate and trustworthy information about smartphones and smartwatches and for tech news also. Have a look.

    ReplyDelete
  28. Awesome! Amazing article, I am going to share this blog immediately, it's really useful, Thank you.
    Realme price in bangladesh

    ReplyDelete
  29. This comment has been removed by the author.

    ReplyDelete
  30. Thank you your article was very helpful for me and my team Blog

    ReplyDelete
  31. Just want to say your article is as astounding. The clearness in your article is just spectacular and i could assume you are well educated in this area of study. The 8th Night (2021) Bangla Subtitle If you allow your authorization allow me to use your RSS feed to keep updated with your new posts. Thanks a bunch and please carry on the gratifying work.

    ReplyDelete
  32. You wrote a nice article you are truly a webmaster sanzydesign

    ReplyDelete
  33. Wonderful article, thanks for putting this together! This is obviously one great post. Thanks for the valuable information and insights you have so provided here. Smartphone Price In Bangladesh

    ReplyDelete
  34. I am really surprised by the quality of your constant posts.You really are a genius, I feel blessed to be a regular reader of such a blog Thanks so much..Plz Visit My Blog- New mobile price bd

    ReplyDelete
  35. In this article, We will show some factors or some features of the fastest methods to get how to use two step verification on hotmail or 2FA. Not only will this help you brush up on your basics of hotmail account, but also learn new things to Save and security of the emails data is one of the biggest benefits of two step verification on Hotmail.

    Read More:
    2FA on Hotmail

    ReplyDelete