0

I'm facing the issue that my Xamarin application "may be doing too much work on its main thread". To circumvent this issue, I'm trying to move some heavy computations to their own separate threads using the RunOnUiThread method. However, I'm currently stuck as I don't really get how to use it properly. What I figured so far is that I have to run this method from my current activity. I try to obtain this activity via:

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

as "Xamarin.Forms.Forms.Context;" is obsolete. Unfortunately, my code only results in the following exception:

System.InvalidCastException: Specified cast is not valid.

Thus, I have two questions:

  1. How do I obtain the current activity?
  2. What's the best way to call the RunOnUiThread method once I have the activity?

Thank you very much for your help.

Hagbard
  • 3,430
  • 5
  • 28
  • 64
  • https://github.com/jamesmontemagno/CurrentActivityPlugin – SushiHangover Mar 07 '19 at 10:34
  • I only get "Could not install package 'Plugin.CurrentActivity 2.1.0.4'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.6,Profile=Profile44', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author." Is there any other way to do this? – Hagbard Mar 07 '19 at 10:42
  • 1
    Use a static var on the MainActivity class : https://stackoverflow.com/a/49524495/4984832 – SushiHangover Mar 07 '19 at 10:48
  • Thank you, that worked even though I had to write an interface first with which I could access this variable from my portable project. However, the problem with runOnUiThread still remains (see below). – Hagbard Mar 07 '19 at 11:26

1 Answers1

1

I was finally able to solve this issue with the following code:

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

, where "AndroidPropertyHandler" is an interface providing access to the static context.

Hagbard
  • 3,430
  • 5
  • 28
  • 64