Application.Current.Properties 在 Xamarin.Forms 应用程序中的 BroadcastReceiver 中

Application.Current.Properties in BroadcastReceiver in Xamarin.Forms application

我在 Application.Current.Properties 中为我的 Xamarin.Forms 应用程序保存了一些首选项,并且有一个需要这些首选项的 BroadcastReceiver。问题是 Xamarin.Forms 没有在 BroadcastReceiver 中初始化,所以我需要一种方法来访问本机 Xamain.Android 中的那些变量。这可能吗?

I need a way to access those variables in native Xamain.Android

您可以使用 DependencyService,此功能使 Xamarin.Forms 应用可以执行本机应用可以执行的任何操作。

这里是使用 Android 的 Toast 在共享代码中显示消息的示例:

1.create 共享代码中的接口:

public interface IToast
 {
    void LongAlert(string message);//the parameter could pass to the native platform
    void ShortAlert(string message);
 }

2.Android 实施:

[assembly: Dependency(typeof(ToastAndroid))]
namespace Demo.Droid
{
  class ToastAndroid : IToast
   {
     public void LongAlert(string message)
      {
        Toast.MakeText(Android.App.Application.Context, message, ToastLength.Long).Show();
      }            

     public void ShortAlert(string message)
      {           
        Toast.MakeText(Android.App.Application.Context, message, ToastLength.Short).Show();
       }
   }
}

3.call 共享代码:

DependencyService.Get<IToast>().ShortAlert("short toast);
DependencyService.Get<IToast>().LongAlert("long toast);

DependencyService

我自己找到了解决方案。 我使用 Xamarin.Forms 源代码(发现 here)编写了一个函数,该函数从写入表单应用程序的同一文件中读取值。很有魅力。