没有Xamarin.Forms的Xamarin BeginInvokeOnMainThread

Syn*_*tax 3 xamarin.android xamarin xamarin.forms

对不起,我相信这将是一个非常愚蠢的问题..

我在我的Xamarin应用程序中使用Android UI而非Xamarin Forms作为表示层,但我想使用Activity.RunOnUIThread(来自Android),所有Xamarin文档都建议使用Device.BeginInvokeOnMainThread(来自Xamarin.Forms)项目.显然我没有这个,因为我没有关于xamarin.forms项目的参考.

如果我不想使用Forms,我在哪里可以找到Xamarin中的run-on-ui-thread机制?

Sus*_*ver 7

安卓:

Android Activity有一个RunOnUiThread你可以使用的方法:

RunOnUiThread  ( () => {
    // manipulate UI controls
});
Run Code Online (Sandbox Code Playgroud)

参考:https://developer.xamarin.com/api/member/Android.App.Activity.RunOnUiThread/p/Java.Lang.IRunnable/

iOS版:

InvokeOnMainThread (delegate {  
    // manipulate UI controls
});
Run Code Online (Sandbox Code Playgroud)


Sve*_*übe 5

如果您想从PCL /共享代码和项目中的其他任何位置执行此操作.你有两种选择.

跨平台方式,使用本机机制

  • 将此添加到PCL

    public class InvokeHelper
    {
        public static Action<Action> Invoker;
    
        public static void Invoke(Action action)
        {
            Invoker?.Invoke(action);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 将此添加到iOS(例如AppDelegate)

    public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        // ...
    
        InvokeHelper.Invoker = InvokeOnMainThread;
        return true;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 将此添加到Android(例如您的应用程序类)

    [Application]
    class MainApplication : Application
    {
        protected MainApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
        {
        }
    
        public override void OnCreate()
        {
            base.OnCreate();
            InvokeHelper.Invoker = (action) =>
            {
                var uiHandler = new Handler(Looper.MainLooper);
                uiHandler.Post(action);
            };
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

然后,您可以使用共享代码进行调用

InvokeHelper.Invoke(() => DoSomething("bla"));
Run Code Online (Sandbox Code Playgroud)

完整的跨平台方式

您也可以实现InvokeHelper跨平台.

public class InvokeHelper
{
    // assuming the static initializer is executed on the UI Thread.
    public static SynchronizationContext mainSyncronisationContext = SynchronizationContext.Current;

    public static void Invoke(Action action)
    {
        mainSyncronisationContext?.Post(_ => action(), null);
    }
}
Run Code Online (Sandbox Code Playgroud)