c# - Xamarin.Android 在后台线程上使用异步方法会导致屏幕闪烁

标签 c# android android-asynctask xamarin.android async-await

所以我正在尝试为我正在创建的应用程序创建一个加载/启动屏幕。基本上,如果用户未经身份验证,那么他们应该无法访问应用程序的其他部分。此外,我希望应用程序在加载主要 Activity 之前尝试同步必要的数据库对象。

问题是,当我调用 Authenticate() 方法和 InitLocalStoreAsync() 方法时,屏幕闪烁(几乎就像 Activity 重新加载,或者就像应用程序正在执行一些我不明白的操作来隐藏 Activity )当方法正在执行时。我希望这种事不要发生。

我对 Android 应用开发非常陌生,甚至对 Xamarin 也比较陌生。

我正在使用来自有关身份验证等的 Azure 移动服务教程的修改后的代码。

我应该使用 RunOnUiThread 以某种方式执行这些方法吗?如果是这样,我如何与 RunOnUiThread 结合使用 wait ?或者我应该以完全不同的方式来做这件事?

我很失落。我尝试搜索并找到要遵循的教程,但我似乎找不到答案。这是到目前为止的代码:

protected override async void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        SetContentView (Resource.Layout.Activity_Splash);
        // Create your application here

        try{
            CurrentPlatform.Init ();

            // Create the Mobile Service Client instance, using the provided
            // Mobile Service URL and key
            client = new MobileServiceClient (applicationURL, applicationKey);
            statusText = FindViewById<TextView> (Resource.Id.SplashStatusText);

            ThreadPool.QueueUserWorkItem(x => Initialize());

        }catch(Java.Net.MalformedURLException){
            CreateAndShowDialog (new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error");
        }catch(Exception e) {
            CreateAndShowDialog (e, "Error");
        }
    }

    private async void Initialize()
    {
        RunOnUiThread(() => statusText.Text = "Authenticating...");
        await Authenticate();

        RunOnUiThread (() => statusText.Text = "Syncing...");
        await InitLocalStoreAsync();

        MoveToMainActivity();
    }

    private async Task Authenticate()
    {
        try
        {
            user = await client.LoginAsync(this, MobileServiceAuthenticationProvider.Google);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

    private async Task InitLocalStoreAsync()
    {
        // new code to initialize the SQLite store
        string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), localDbFilename);

        if (!File.Exists(path))
        {
            File.Create(path).Dispose();
        }

        var store = new MobileServiceSQLiteStore(path);
        store.DefineTable<ToDoItem>();

        // Uses the default conflict handler, which fails on conflict
        // To use a different conflict handler, pass a parameter to InitializeAsync. For more details, see http://go.microsoft.com/fwlink/?LinkId=521416
        await client.SyncContext.InitializeAsync(store);
    }

我该如何重组它,这样我就不会出现任何屏幕闪烁?

最佳答案

如果你想运行异步方法,你必须使用任务工厂:

RunOnUiThread(() => statusText.Text = "Loading.");
Task.Run(() => AsyncWork()).ContinueWith(result => RunOnUiThread(() => statusText.Text = "Done!"));

屏幕闪烁我认为这可能是两件事,应用程序崩溃并正在尝试恢复最后一个 Activity ,或者您正在尝试更新 UI 线程上的元素并进行处理/工作,所以它可能是“口吃” .

关于c# - Xamarin.Android 在后台线程上使用异步方法会导致屏幕闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28491100/

相关文章:

c# - 扩展基类型并自动更新实体的审计信息

android - 更新 ListView 中的进度条

android - 使用 RecyclerView 时 notifydatasetchanged 是否调用 onCreateViewHolder

android - "Unsupported type ' PreferenceActivity ' in file"Android

android - 无法在 AsyncTask 中访问 "findViewById"

c# - 远程属性验证未在 Asp.Net MVC 中触发

c#比较两个对象模型中的数据

java - 使用 AsyncTask 时出现运行时异常

android - 获取 IndexOutOfBoundException : Invalid array range 0 to 0 , 所以上下文 = null,所以应用程序崩溃

c# - 从数据库中打开 word 文档(保存为二进制文件)