Xamarin.Android:启动活动并等待结果

奥利维尔·马特罗(Olivier MATROT)

我需要启动一项活动,要求用户授予应用节电豁免。用户必须回答“是”才能继续:

这是我到目前为止拥有的-buggy-代码:

   PowerManager pm = (PowerManager)Android.App.Application.Context.GetSystemService(Context.PowerService);
        while (!pm.IsIgnoringBatteryOptimizations(this.ApplicationContext.PackageName))
        {
            IPopupService popupService = Locator.GetSharedInstance<IPopupService>();
            await popupService.DisplayAlertAsync(
                BusinessResources.GoToPowerSettingsTitle,
                BusinessResources.GoToPowerSettingsMessage,
                BusinessResources.Ok).ConfigureAwait(true);
            using (var intent = new Intent(Android.Provider.Settings.ActionRequestIgnoreBatteryOptimizations, Android.Net.Uri.Parse("package:" + Forms.Context.PackageName)))
            {
                Forms.Context.StartActivity(intent);
            }
        }

由于StartActivity不会等待,因此我将向用户询问一次以上的需求。

现在,我搜索了可能的解决方案,并找到了ActivityTaskActivityController

我现在很困惑。如果Xamarin Forms即将推出,我应该使用哪一个?

奥利维尔·马特罗(Olivier MATROT)

好的,我通过在启动活动后等待AsyncAutoResetEvent解决了我的问题

定义了一个事件以及一个握手值:

   private AsyncAutoResetEvent dozeStandby;
   private int dozeStandbyHandshake = nameof(dozeStandbyHandshake).GetHashCode(StringComparison.InvariantCultureIgnoreCase);

在创建活动期间,我提示用户允许设置。因为我使用的是StartActivityForResult,所以在提示活动结束时将调用OnActivityResult:

    protected override async void OnCreate(Bundle bundle)
    {
        dozeStandby = new AsyncAutoResetEvent();

        PowerManager pm = (PowerManager)Android.App.Application.Context.GetSystemService(Context.PowerService);
        while (!pm.IsIgnoringBatteryOptimizations(this.ApplicationContext.PackageName))
        {
              IPopupService popupService = Locator.GetSharedInstance<IPopupService>();
              await popupService.DisplayAlertAsync(
                        BusinessResources.GoToPowerSettingsTitle,
                        BusinessResources.GoToPowerSettingsMessage,
                        BusinessResources.Ok).ConfigureAwait(true);
              using (var intent = new Intent(Android.Provider.Settings.ActionRequestIgnoreBatteryOptimizations, Android.Net.Uri.Parse("package:" + Android.App.Application.Context.PackageName)))
              {
                  this.StartActivityForResult(intent, dozeStandbyHandshake);
                  await this.dozeStandby.WaitAsync().ConfigureAwait(true);
              }
         }
    }

在这里,我检查握手以设置事件。

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if (requestCode == dozeStandbyHandshake)
        {
            this.dozeStandby.Set();
        }
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章