【问题标题】:Xamarin Android Forms.Context obsolete - How to fix it in a dependent method?Xamarin Android Forms.Context 已过时 - 如何在依赖方法中修复它?
【发布时间】:2019-06-07 00:09:57
【问题描述】:

我收到一条消息说 FormsContext 已过时。我看到了很多关于如何解决它的建议,但没有一个适用于我的案例:

[assembly: Xamarin.Forms.Dependency(typeof(SoundMethods))]
namespace J.Droid
{
    public class SoundMethods : ISoundMethods
    {
        public void IsDeviceSilent()
        {
            AudioManager am = (AudioManager)Forms.Context.GetSystemService(Context.AudioService);
        }
    }
}

谁能建议我如何解决这个问题?

【问题讨论】:

  • 试试 Android.App.Application.Context 而不是 Forms.Context

标签: xamarin xamarin.forms


【解决方案1】:

我通常使用 James Montemagno 的 Plugin.CurrentActivity。

Nuget:https://www.nuget.org/packages/Plugin.CurrentActivity

Github:https://github.com/jamesmontemagno/CurrentActivityPlugin

您必须在 AppDelegate OnCreate 中初始化插件:

CrossCurrentActivity.Current.Init(this, bundle);

然后在您的服务(或 Android 项目中的任何类)中,您可以通过以下方式获取当前上下文:

var context = CrossCurrentActivity.Current.AppContext

【讨论】:

    【解决方案2】:

    您可以像这样在构造函数中获取上下文:

    private Context _context;
    
    public ContentPageRenderer(Context context) : base(context)
    {
        _context = context;
    }
    

    然后使用_context 变量访问它。

    【讨论】:

    • 我认为这不适用于 DependencyService。
    • 这个答案是给渲染器的,问题是关于在 Forms 项目中与 DI 一起使用的服务
    • @Arvindraja 这适用于 DependencyService,我在我的应用程序中使用它
    • @GiampaoloGabba 没关系,这在服务中也可以正常工作。
    【解决方案3】:

    您可以添加一个方法来初始化并从 MainActivity 传递上下文:

      static Context _context;
    
            public static void Init(Context context)
            {
                _context = context;
            }
    
    
            public void IsDeviceSilent()
            {
                AudioManager am = (AudioManager)_context.GetSystemService(Context.AudioService);
            }
    

    那么,在MainActivity

    SoundMethods.Init(this);
    

    您可以在here了解更多信息

    【讨论】:

    • 我很困惑。这是一个 Xamarin Forms 应用程序,我没有 Init。你能解释更多吗?
    • 一个 xamarin 表单应用程序,具有 Xamarin.Android 应用程序。你在哪里创建这个类?在 Android 或 Forms 中?
    • 在 Xamarin Forms 应用的 Android 项目中。
    • 所以,你有一个 MainActivity 文件,你应该按照我在答案中所说的去做......
    猜你喜欢
    • 2018-05-19
    • 2019-12-14
    • 2021-07-14
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多