在Xamarin.Forms中访问Android上下文

B B*_*est 7 android android-context xamarin.android xamarin xamarin.forms

我已经看到了一些使用Xamarin.Forms获取Android Context的旧解决方案.这些较旧的解决方案建议使用,Xamarin.Forms.Forms.Context但由于不断变化的Xamarin.Forms平台,这不再适用.

在我的示例中,我使用了DependencyService.Get<Interface>()来自我的共享代码项目来使用Interface该类的特定于平台的实现.

当使用Xamarin.Andriod使用特定于平台的功能时,需要使用Android Context.

那么我们如何获得Android Context的全局信息界面呢?

B B*_*est 16

  1. 转到您在解决方案的App.Droid项目部分中创建的类.
  2. 确保您已using Android.Content;包含在顶部.
  3. 创建一个变量来保存Context并使用它进行初始化Android.App.Application.Context.

而已!

using Android.Content;

[assembly: Xamarin.Forms.Dependency(typeof(DroidClass))]
namespace App.Droid
{
   public class DroidClass : Interface
   {
     Context context = Android.App.Application.Context;

     public DroidClass()
     {
        Toast.MakeText(context, "Grabbed Context!", ToastLength.Long).Show();
         }  
      }
   }
Run Code Online (Sandbox Code Playgroud)

  • 为了确保不会发生内存泄漏,我总是喜欢在使用上下文时都放入弱引用。记住要检查是否为Null(如果已被垃圾回收)。WeakReference &lt;Context&gt; context =新的WeakReference &lt;Context&gt;(Application.Context); (2认同)