【问题标题】:Issues with RunOnUiThread MethodRunOnUiThread 方法的问题
【发布时间】:2019-03-07 21:16:16
【问题描述】:

我面临的问题是我的 Xamarin 应用程序“may be doing too much work on its main thread”。为了规避这个问题,我尝试使用RunOnUiThread 方法将一些繁重的计算转移到它们自己的单独线程中。但是,我目前陷入困境,因为我真的不知道如何正确使用它。到目前为止,我认为我必须从我当前的活动中运行这个方法。我尝试通过以下方式获得此活动:

var activity = (Activity)Android.App.Application.Context;

作为“Xamarin.Forms.Forms.Context;”是obsolete。不幸的是,我的代码只导致以下异常:

System.InvalidCastException:指定的强制转换无效。

因此,我有两个问题:

  1. 如何获取当前活动?
  2. 拥有活动后调用 RunOnUiThread 方法的最佳方式是什么?

非常感谢您的帮助。

【问题讨论】:

  • 我只收到“无法安装包 'Plugin.CurrentActivity 2.1.0.4'。您正在尝试将此包安装到针对 '.NETPortable,Version=v4.6,Profile=Profile44 的项目中',但包不包含任何与该框架兼容的程序集引用或内容文件。有关详细信息,请联系包作者。有没有其他方法可以做到这一点?
  • 在 MainActivity 类上使用静态变量:stackoverflow.com/a/49524495/4984832
  • 谢谢,尽管我必须先编写一个接口,以便我可以从我的可移植项目中访问这个变量,但它仍然有效。但是,runOnUiThread 的问题仍然存在(见下文)。

标签: c# android xamarin


【解决方案1】:

我终于可以用下面的代码解决这个问题了:

        Context Context = DependencyService.Get<AndroidPropertyHandler>().GetMainActivityContext();
        var Activity = (Activity) Context;
        Runnable MyRunnable = new Runnable(() => {
            Debug.WriteLine("My work goes here...");
        });
        Activity.RunOnUiThread(MyRunnable);

,其中“AndroidPropertyHandler”是提供对静态上下文的访问的接口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2013-10-25
    • 1970-01-01
    相关资源
    最近更新 更多