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

Owais Ahmed 81 Reputation points
2021-03-19T16:42:22.017+00:00

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();

            }
        }


        }
    }
    }
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,371 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,210 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JessieZhang-MSFT 7,711 Reputation points Microsoft Vendor
    2021-03-23T03:04:57.75+00:00

    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.

    0 comments No comments

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.