Send string from Android project to PCL with MessagingCenter

泄露秘密 提交于 2020-03-23 15:32:10

问题


This is my first post on this forum so any tips on how to make the question more understandable/readable and so on is appreciated.

What am I doing?

I am making my first app using Xamarin Forms, and I have two projects, PCL (Portable Class Library) and Android. My Android project receives incoming SMS from a specific number and saves it to a string. What I am trying to achieve is that by using MessagingCenter, send the string from my Android project to my PCL.

My problem:

I have seen a lot of threads regarding this, but there is something I am missing. And because I am new to this forum I can't write comments so I have to create my own question. Let me show you some of the code. (parsedsms is the string containing the SMS)

SmsReceiver.cs (In my Android project)

MessagingCenter.Send<SmsReceiver, string> (this, "ParsedSmsReceived", parsedsms);

MissionPage.xaml.cs (In my PCL project)

MessagingCenter.Subscribe<SmsReceiver, string> (this, "ParsedSmsReceived",
(sender, arg) => 
{ 
    string message = arg; 
});

This is an example that I found on another thread here on Stackoverflow. My problem is that parsedsms can't be accessed from the PCL. How can I access the SmsReceiver class from my PCL? You can't add a reference from PCL (because it is a library I guess) to Android, only the other way around.


回答1:


As @Jason wrote in the comments, the solution is to use Object instead of SmsReceiver like this:

SmsReceiver.cs

MessagingCenter.Send<Object, string> (this, "ParsedSmsReceived", parsedsms);

MissionPage.xaml.cs

MessagingCenter.Subscribe<Object, string> (this, "ParsedSmsReceived",
(sender, arg) => 
{ 
    string message = arg; 
});

This works fine, but if MessagingCenter actually is the right way to go is another question. As @Csharpest commented using DependencyService might be a better solution.




回答2:


The interface makes it possible to better manage the message.

ISmsReceiver.cs in PCL

public interface ISmsReceiver {}

SmsReceiver.cs in Android

[assembly: Dependency(typeof(SmsReceiver ))]
namespace App1.MobileApp.Droid
{
    public class SmsReceiver : BroadcastReceiver, ISmsReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            MessagingCenter.Send<ISmsReceiver, string> (this, "ParsedSmsReceived", parsedsms);
        }
    }
}

MissionPage.xaml.cs in PCL

MessagingCenter.Subscribe<ISmsReceiver, string> (this, "ParsedSmsReceived",
(sender, arg) => 
{ 
    string message = arg; 
});


来源:https://stackoverflow.com/questions/49195058/send-string-from-android-project-to-pcl-with-messagingcenter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!