我在Xamarin.Android中收到消息,我需要将其传递给Xamarin.Forms应用。我现在想出的是依赖注入。我已经定义了接口:
public interface IReceived
{
event OnReceived Received;
}
以及它的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);
}
}
}
而且我已经订阅了事件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)
{
// ...
}
这项工作没有出现任何错误。但是,当升起时,Received?.Invoke(XMessages);
线始终为null
。而且我无法在主应用程序Xamarin.Forms中捕获该事件(消息时刻到来)
该怎么做?
同意Jason,您可以使用MessagingCenter
实现它。这是[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");
}
}
您可以收到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();
}
}
这是我正在跑步的gif。
这里是代码演示代码(注意:我没有获得运行时权限,您应该手动添加该权限。)>