在Xamarin.Forms中访问Android上下文

19

我曾看到一些旧的解决方案用于获取 Xamarin.Forms 中的 Android 上下文。这些较旧的解决方案建议使用 Xamarin.Forms.Forms.Context,但由于 Xamarin.Forms 平台不断变化,此方法已经失效。

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

在使用 Xamarin.Andriod 时,使用 Android 上下文需要大量相关平台的功能。

那么我们如何为 Android 上下文获得全局信息接口呢?

1个回答

50
  1. 进入你在App.Droid项目中创建的类。
  2. 确保你已经在顶部包含了using Android.Content;
  3. 创建一个变量来保存上下文并用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();
         }  
      }
   }

4
为了确保不出现内存泄漏,每当我使用上下文(Context)时,我总是喜欢添加一个弱引用(Weak Reference)。如果已经被垃圾回收机制清理掉,请记得检查是否为空(null)。代码示例: WeakReference<Context> context = new WeakReference<Context>(Application.Context); - Clinton Rocksmith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接