简体   繁体   English

将变量值从 Xamarin.Android 传递到 Xamarin.Forms

[英]Pass variable values from Xamarin.Android to Xamarin.Forms

I get messages in Xamarin.Android and I need pass it to Xamarin.Forms app.我在 Xamarin.Android 中收到消息,我需要将其传递给 Xamarin.Forms 应用程序。 What I came up with at the moment is dependency injection.我现在想到的是依赖注入。 I has defined the interface:我已经定义了接口:

public interface IReceived
{
    event OnReceived Received;
}

And its implementation inside IncomingSms class inherited from BroadcastReceiver for messages listening及其在 IncomingSms 类中的实现从 BroadcastReceiver 继承,用于消息侦听

[assembly: Dependency(typeof(XxmsApp.Api.IncomingSms))]
namespace XxmsApp.Api
{


    // [BroadcastReceiver(Enabled = true, Exported = true)]

    [BroadcastReceiver(Enabled = true, Label = "SMS Receiver")]
    [IntentFilter(new string [] { Telephony.Sms.Intents.SmsReceivedAction })]           // "android.provider.Telephony.SMS_RECEIVED"
    public class IncomingSms : BroadcastReceiver, IReceived
    {

        public event OnReceived Received;

        public override void OnReceive(Context context, Intent intent)
        {

            if (intent.Action != Telephony.Sms.Intents.SmsReceivedAction) return;

            SmsMessage[] messages = Telephony.Sms.Intents.GetMessagesFromIntent(intent);

            OnMessagesReiceved(messages);

        }

        private void OnMessagesReiceved(SmsMessage[] messages)
        {

            var smsMesages = new List<(string Address, string Message)>();
            var XMessages = new List<XxmsApp.Model.Message>();

            for (var i = 0; i < messages.Length; i++)
            {
                smsMesages.Add((messages[i].OriginatingAddress, messages[i].MessageBody));


                XMessages.Add(new XxmsApp.Model.Message
                {
                    Address = messages[i].OriginatingAddress,
                    Value = messages[i].MessageBody
                });

            }

            Received?.Invoke(XMessages);

        }
    }
}

And I have subscribed to the event Received我已经订阅了Received事件

    public App()
    {

        DBUpdates();

        MainPage = (new MasterDetailPage()
        {
            Master = new MenuPage { Title = "Title" },
            Detail = new NavigationPage(new XxmsApp.MainPage()) { BarBackgroundColor = Color.Black }
        });

        xMessages = DependencyService.Get<XxmsApp.Api.IReceived>();
        xMessages.Received += XMessages_Received;//*/

    }

    private void XMessages_Received(IEnumerable<Model.Message> message)
    {
          // ...
    }

It's work without some errors.它的工作没有一些错误。 But when raised the line Received?.Invoke(XMessages);但是当提出行Received?.Invoke(XMessages); Received always is null . Received 始终为null And I can't catch the event (moment of message coming) in my main app Xamarin.Forms而且我无法在我的主应用程序 Xamarin.Forms 中捕捉到事件(消息到来的时刻)

How can do this?怎么能做到这一点?

Agree with Jason, you can use the MessagingCenter to achieve it.同意 Jason,您可以使用MessagingCenter来实现它。 Here is code in the SmsBroadcastRceiver这是SmsBroadcastRceiver代码

    [BroadcastReceiver(Enabled = true, Exported = true)]
    [IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED" })]
    public class SmsBroadcastRceiver : BroadcastReceiver
    {

        public SmsBroadcastRceiver()
        {

        }



        public override void OnReceive(Context context, Intent intent)
        {
            var msgs = Telephony.Sms.Intents.GetMessagesFromIntent(intent);

            List<string> msgList = new List<string>();
            foreach (var msg in msgs)
            {
                msgList.Add(msg.DisplayMessageBody);

            }

            MessagingCenter.Send<List<string>>(msgList, "MyMessage");
        }
    }

You can receive the message in PCL background code.您可以在 PCL 后台代码中接收消息。

    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            MessagingCenter.Subscribe<List<string>>(this, "MyMessage", (expense) =>
            {
                List<string> mylist= expense as List<string>;
                string allText= "";
                foreach (string item in mylist)
                {
                    allText += item+"  ";
                }
                editorSms.Text = allText;
            });



        }



        private void Button_Clicked(object sender, EventArgs e)
        {
            Xamarin.Forms.DependencyService.Get<ISmsReader>().GetSmsInbox();
        }
    }

Here is my running gif.这是我的跑步 gif。

在此处输入图片说明

Here is code demo code(Note:I do not achieve the runtime permission, you should add the permission manually).这是代码演示代码(注意:我没有实现运行时权限,您应该手动添加权限)。

https://github.com/851265601/BroadcastReceSMS https://github.com/851265601/BroadcastReceSMS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM