使用MessagingCenter将字符串从Android项目发送到PCL [英] Send string from Android project to PCL with MessagingCenter
问题描述
这是我在该论坛上的第一篇文章,因此,任何有关使问题更易于理解/理解的技巧都将受到赞赏.
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.
我在做什么?
我正在使用Xamarin Forms创建我的第一个应用程序,我有两个项目,PCL(便携式类库)和Android.我的Android项目从特定号码接收传入的SMS,并将其保存为字符串.我想要实现的是通过使用MessagingCenter将字符串从我的Android项目发送到PCL.
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.
我的问题:
我已经看到了很多与此相关的话题,但是我缺少了一些东西.而且由于我是这个论坛的新手,所以我无法写评论,因此我必须创建自己的问题.让我向您展示一些代码. (parsedsms
是包含SMS的字符串)
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(在我的Android项目中)
SmsReceiver.cs (In my Android project)
MessagingCenter.Send<SmsReceiver, string> (this, "ParsedSmsReceived", parsedsms);
MissionPage.xaml.cs(在我的PCL项目中)
MissionPage.xaml.cs (In my PCL project)
MessagingCenter.Subscribe<SmsReceiver, string> (this, "ParsedSmsReceived",
(sender, arg) =>
{
string message = arg;
});
这是我在Stackoverflow上另一个线程上找到的示例.我的问题是无法从PCL访问parsedsms
.如何从PCL访问SmsReceiver类?您不能从PCL(因为我猜它是一个库)向Android添加引用,只能相反.
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.
推荐答案
就像@Jason在评论中所写的那样,解决方案是使用Object
而不是SmsReceiver
这样:
As @Jason wrote in the comments, the solution is to use Object
instead of SmsReceiver
like this:
SmsReceiver.cs
SmsReceiver.cs
MessagingCenter.Send<Object, string> (this, "ParsedSmsReceived", parsedsms);
MissionPage.xaml.cs
MissionPage.xaml.cs
MessagingCenter.Subscribe<Object, string> (this, "ParsedSmsReceived",
(sender, arg) =>
{
string message = arg;
});
这很好,但是如果MessagingCenter实际上是正确的方法,则是另一个问题.正如@Csharpest所说,使用DependencyService可能是更好的解决方案.
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.
这篇关于使用MessagingCenter将字符串从Android项目发送到PCL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!