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.
Answers
To listen the receive sms, try using a broadCastReceiver like below:
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.
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.
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.