How to Read OTP from messages and Autofill entry in .NET 8 MAUI(iOS and Android)

Satya 160 Reputation points
2024-09-10T05:11:05.1333333+00:00

How to Read OTP from messages and Autofill entry in .NET 8 MAUI(iOS and Android)?

Thanks in advance :)

Developer technologies | .NET | .NET MAUI
{count} vote

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2024-09-11T07:32:18.7166667+00:00

    Hello,

    Due to the permission control of iOS, no Application can read the user's text messages. Therefore, this feature is available in Android.

    You can refer to the following example to learn how to receive the latest SMS on the Android platform and update the content to Entry.

    Step 1. Add permissions:

    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    

    Step 2. Since reading SMS is a dangerous permission, you also need to dynamically request permission in the MainActivity to use this feature with the user's consent.

    public class MainActivity : MauiAppCompatActivity
    {
        protected override async void OnCreate(Bundle? savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            await CheckAndRequestSMSPermission();
        }
     
        public async Task<PermissionStatus> CheckAndRequestSMSPermission()
        {
            PermissionStatus status = await Permissions.CheckStatusAsync<Permissions.Sms>();
     
            if (status == PermissionStatus.Granted)
                return status;
     
            if (status == PermissionStatus.Denied && DeviceInfo.Platform == DevicePlatform.iOS)
            {
                // Prompt the user to turn on in settings
                // On iOS once a permission has been denied it may not be requested again from the application
                return status;
            }
     
            if (Permissions.ShouldShowRationale<Permissions.Sms>())
            {
                // Prompt the user with additional information as to why the permission is needed
            }
            status = await Permissions.RequestAsync<Permissions.Sms>();
            return status;
        }
    }
    

    Step 3. Add an SMS receiver to receive a response in the form of a broadcast, and send a message to the subscriber via WeakReferenceMessage to read the latest SMS. You could refer to Messenger for more detailed information.

    [BroadcastReceiver(Exported = true,Enabled = true, Label = "SMS Receiver")]
    [IntentFilter(new string[] { "android.provider.Telephony.SMS_RECEIVED", Intent.CategoryDefault })]
    public class SmsReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            WeakReferenceMessenger.Default.Send(new ReceiveSMSMessage(1));
        }
     
     
    }
    
    // Message class
    public class ReceiveSMSMessage : ValueChangedMessage<int>
        {
            public ReceiveSMSMessage(int count) : base(count)
            {
            }
        }
    

    Step 4. Subscribe to the Message in the page where you need to respond to the SMS, and update the text in the Entry.

            public MainPage()
            {
                InitializeComponent();
                WeakReferenceMessenger.Default
        .Register<MainPage, ReceiveSMSMessage>(
            this,
            async (recipient, message) =>
            {
    #if ANDROID
                List<string> items = new List<string>();
                string INBOX = "content://sms/inbox";
                string[] reqCols = new string[] { "_id", "thread_id", "address", "person", "date", "body", "type" };
                Android.Net.Uri uri = Android.Net.Uri.Parse(INBOX);
                Android.Database.ICursor cursor = Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.ContentResolver.Query(uri, reqCols, null, null, null);
                if (cursor != null && cursor.MoveToFirst()) {
                    string body = cursor.GetString(cursor.GetColumnIndex("body"));
                    test_entry.Text = body;
                }
    #endif
            });
            }
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.