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.
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.