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.