question

OwaisAhmed-0825 avatar image
0 Votes"
OwaisAhmed-0825 asked RobCaplan edited

How do I receive sms on Textview on an incoming message ??

Hi, I've made this simple app for recieving sms,When I receive a message I want to output this on my TextView,upuntil now for testing I was just doing
that inside a button .You recieve a message ,click on the button and you get the sms on textview.If I try to do this without a button ,at the start of compilation
I get a null reference exception.Can anyone help me on this ?

 //----------MainActivity.cs---------------
        
  using Android.App;
 using Android.OS;
 using Android.Support.V7.App;
 using Android.Runtime;
 using Android.Widget;
 using Android.Content;
 using Android.Telephony;
 using Android.Provider;
 using Android.Util;
 using Java.Lang;
 using System.Text.RegularExpressions;
 using Xamarin.Essentials;
 using System;
 using Android;
 using Android.Support.V4.Content;
 using Android.Content.PM;

 namespace Sms_Receiver2
 {
 [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
 public class MainActivity : AppCompatActivity
 {

     public Receiver1 _receiver;            // Receiver class 
     protected override void OnCreate(Bundle savedInstanceState)
     {
         base.OnCreate(savedInstanceState);
         Xamarin.Essentials.Platform.Init(this, savedInstanceState);
         // Set our view from the "main" layout resource
         SetContentView(Resource.Layout.activity_main);


         TextView translatedPhoneWord = FindViewById<TextView>(Resource.Id.TranslatedPhoneword);
         Button translateButton = FindViewById<Button>(Resource.Id.TranslateButton);


         if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadSms) != (int)Permission.Granted)
         {
             RequestPermissions(new string[] { Manifest.Permission.ReadSms, Manifest.Permission.SendSms, Manifest.Permission.ReceiveSms }, 0);
         }

         translateButton.Click += (s, e) =>
         {

             translatedPhoneWord.Text = _receiver.message;     
             // Toast.MakeText(ApplicationContext, _receiver.address + ", " + _receiver.message, ToastLength.Short).Show();     //showing a Toast again 

         };


     }
     public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
     {
         Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

         base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
     }


     protected override void OnResume()
     {

         base.OnResume();
         _receiver = new Receiver1();
         IntentFilter filter = new IntentFilter();
         filter.AddAction("android.provider.Telephony.SMS_RECEIVED");
         filter.AddAction("android.provider.Telephony.SMS_DELIVER");
         RegisterReceiver(_receiver, filter);
     }

     protected override void OnPause()
     {
         base.OnPause();
         UnregisterReceiver(_receiver);


     }

     }
     }         


       //---------Reciever.cs -------------

           using Android.App;
 using Android.Content;
 using Android.OS;
 using Android.Runtime;
 using Android.Views;
 using Android.Widget;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using Android.Telephony;
 using Android.Provider;

 namespace Sms_Receiver2
 {
 [BroadcastReceiver(Enabled = true, Exported = true, Permission = "android.permission.BROADCAST_SMS")]
 [IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED", "android.provider.Telephony.SMS_DELIVER" }, Priority = (int)IntentFilterPriority.HighPriority)]
 public class Receiver1 : 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();

             }
         }

           
         }
     }
     }




dotnet-csharpdotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JessieZhang-2116 avatar image
0 Votes"
JessieZhang-2116 answered JessieZhang-2116 edited

Hello,


Welcome to our Microsoft Q&A platform!

A method is to define a static reference of your activity inside your activity, and call the update function in your broadcast receiver.

You can refer the following code:

 public class MainActivity : AppCompatActivity
  {
     //define an instance of current activity
      public static MainActivity Instance;
      protected override void OnCreate(Bundle savedInstanceState)
      {
          base.OnCreate(savedInstanceState);
          Xamarin.Essentials.Platform.Init(this, savedInstanceState);
          // Set our view from the "main" layout resource
          SetContentView(Resource.Layout.activity_main);
          Instance = this;
      }
     // define a method in your activity
      public void updateUI(string value) { 
      // here you can update the UI
            
            
       }
     }

And in your BroadcastReceiver, do like this:

  [BroadcastReceiver(Enabled = true, Exported = true, Permission = "android.permission.BROADCAST_SMS")]
  [IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED", "android.provider.Telephony.SMS_DELIVER" })]
  public class Receiver1: BroadcastReceiver
  {
      public override void OnReceive(Context context, Intent intent)
      {
          string result = " test";
          MainActivity.Instance.updateUI(result);
      }
   }

A simple method is to use MessagingCenter to achieve this.

You can add the following code in your app.

1.Subscribe message in method OnCreate of MainActivity:

       MessagingCenter.Subscribe<Receiver1, List<string>>(this,
      "msg", (sender, values) =>
     {
         if (values != null && values.Count > 0)
         {
             foreach (string item in values) {
                 translatedPhoneWord.Text = item;
                 Toast.MakeText(ApplicationContext, " message = " + item, ToastLength.Short).Show();
             }
         }
     });

2.Send message in Receiver1 of your app:

        public override void OnReceive(Context context, Intent intent)
       {
         var msgs = Telephony.Sms.Intents.GetMessagesFromIntent(intent);
         List<string> msgList = new List<string>();
         string address = "";
         string body = "";
         foreach (var msg in msgs)
         {
             msgList.Add(msg.DisplayMessageBody);
             address = msg.DisplayOriginatingAddress;
             body = msg.DisplayMessageBody;
         }
         markMessageRead(Android.App.Application.Context, address, body);
         Text = body;
         Toast.MakeText(context, "Number :" + address + "Message : " + body, ToastLength.Short).Show();

      // send mesage here
         MessagingCenter.Send<Receiver1,List<string>>(this, "msg", msgList);
     }

Note: I installed nuget xamarin forms (4.5.0.725) on your app to test.


Best Regards,

Jessie Zhang


If the response is helpful, please click "Accept Answer" and upvote it.


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.






5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.