Search code examples
c#androidxamarin.formsxamarin.androidsms

Listen to all SMSes and do something when the definite message is received in Xamarin Android


I want my android app to listen in all incoming messages and do what it is supposed to do when it receives the intended message. For example, I want to send the location of the phone to a preset number when it receives the message that the phone is missing, I do not care from which number it receives the message, only the message that will sent should be send to the specified number (for example my second number). I wrote the messaging codes and they are in the program and my only problem is receiving the messages and distinguishing them from each other and separating the correct message.

I apologize if my question is superficial or my explanation is inaccurate. I'm new in Xamarin and I have not become a professional yet. If the explanation is not complete, tell me where the problem is, I will explain more. Thanks


Solution

  • You could try to use BroadcastReceiver(android.provider.Telephony.SMS_RECEIVED) to listener the SMSes.

    For more detail information, please refer to the official document: Broadcast Receivers in Xamarin.Android.

    Something like:

    [BroadcastReceiver(Enabled = true)]
    [IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED" })]
    class SMSBroadcastReceiver: BroadcastReceiver
    {
        public static string IntentAction = "android.provider.Telephony.SMS_RECEIVED";
        public override void OnReceive(Context context, Intent intent)
        {
           if (intent.Action != SmsRetriever.SmsRetrievedAction)
            return;
    
           var extrasBundleundle = intent.Extras;
           if (extrasBundleundle == null) return;
           var status = (Statuses)extrasBundleundle.Get(SmsRetriever.ExtraStatus);
           switch (status.StatusCode)
             {
                case CommonStatusCodes.Success:
                // Get SMS message contents
                var messageContent = (string)extrasBundleundle.Get(SmsRetriever.ExtraSmsMessage);
                
                  break;
    
                case CommonStatusCodes.Timeout:
                
                  break;
             }          
        }
    }
    

    don't forget to add the permission <uses-permission android:name=”android.permission.RECEIVE_SMS”/>