Forum Xamarin.Android

Sms Receive Permissions

Ow19mOw19m Member ✭✭

Can Anyone tell me how I can write a program for permissions to Receive an sms from my App on Xamarin android ??Thanks .

Answers

  • YelinzhYelinzh Member, Xamarin Team Xamurai

    To listen the receive sms, try using a broadCastReceiver like below:

    [BroadcastReceiver(Label = "SMS Receiver", Enabled = true, Exported = true)]
    [IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED" }, Priority = (int)IntentFilterPriority.HighPriority)]
    public class CustomReceiver : BroadcastReceiver
    {
        public string message, address = "";
        public static readonly string INTENT_ACTION = "android.provider.Telephony.SMS_RECEIVED";
        public override void OnReceive(Context context, Intent intent)
        {
            if (intent.HasExtra("pdus"))
            {
                var smsArray = (Java.Lang.Object[])intent.Extras.Get("pdus");
                foreach (var item in smsArray)
                {
                    var sms = SmsMessage.CreateFromPdu((byte[])item);
                    address = sms.OriginatingAddress;
                    message = sms.MessageBody;
                    Toast.MakeText(context, "Number : " + address + ",Message : " + message, ToastLength.Short).Show();
                }
            }
        }
    }
    

    If you test the code on Android api 23+, it requires to grant the permissions at runtime.


    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • Ow19mOw19m Member ✭✭
    edited February 10

    android is considering sms related application as a dangerous permission, I have used the above code but it does not work,I am using android 9.0.

  • YelinzhYelinzh Member, Xamarin Team Xamurai

    For Android 9.0, you should change your application as SMS default application to read the sms. Or using ContentProvider to get the SMS info.

Sign In or Register to comment.