我正在尝试修补现有的基于 Xamarin.Android Forms 的应用程序,以便与 Android 10 设备配合使用。
我们在应用程序中只有一个 Activity ,并且我们使用表单导航系统来推送和弹出警报页面。
我们有一个后台服务,可以请求主 Activity 推送新页面并中断前 10 台设备上的用户。
由于我们无法再打扰运行 Android 10 的用户,因此我们决定采用 Google recommended route 。我找到了this previous answer获取实现示例。
Android 10 之前的代码基本上是这样的:
// post on ui thread
Android.App.Application.SynchronizationContext.Post(
_ =>
{
Intent intent = new Intent(this.applicationContext, typeof(MainActivity));
// intent.AddFlags(ActivityFlags.NoHistory);
intent.AddFlags(ActivityFlags.FromBackground);
intent.AddFlags(ActivityFlags.NewTask);
this.applicationContext.StartActivity(intent);
},
null);
新代码变为:
var builder = new NotificationCompat.Builder(context: this.applicationContext, channelId: channelId);
builder.SetContentTitle(title: notification.Title);
builder.SetContentText(text: notification.Text);
builder.SetSmallIcon(icon: this.resourceManager.GetImage(resourceName: notification.Icon));
builder.SetPriority(pri: notification.Priority);
builder.SetAutoCancel(autoCancel: true);
Intent nextScreen = new Intent(this.applicationContext, typeof(MainActivity));
PendingIntent intent = PendingIntent.GetActivity(
context: this.applicationContext,
requestCode: 0,
intent: nextScreen,
flags: PendingIntentFlags.OneShot);
builder.SetFullScreenIntent(intent: intent, highPriority: true);
this.notificationManager.Notify(id: notification.Id, notification: builder.Build());
但是新代码不起作用。
发生的情况是通知显示在通知区域中而不是全屏。
我的印象是我需要使用新的 Activity。
我不能使用应用根 Activity 吗?
最佳答案
更新 1:此代码适用于 Android 10 之前的设备,无论设备是否锁定、应用程序是否在前台。
使用此新代码可以部分工作(不在锁定屏幕上):
var manager = (Android.App.AlarmManager)this.applicationContext.GetSystemService(Context.AlarmService);
using (var calendar = Calendar.Instance)
{
calendar.Add(CalendarField.Second, 1);
Intent fullScreenIntent = new Intent(this.applicationContext, typeof(MainActivity));
PendingIntent fullScreenPendingIntent = PendingIntent.GetActivity(
this.applicationContext,
0,
fullScreenIntent,
PendingIntentFlags.OneShot);
manager.SetExact(AlarmType.RtcWakeup, calendar.TimeInMillis, fullScreenPendingIntent);
}
更新 2:一个可行的解决方案是简单地请求应用程序的 OverlayPermission 并坚持使用旧代码(问题的第一 block )。
启动时我们调用以下新方法:
private async Task ManageOverlayPermissionAsync()
{
IPopupService popupService = Locator.GetSharedInstance<IPopupService>();
if (BusinessHelper.AndroidMajorVersion >= 10 && !Android.Provider.Settings.CanDrawOverlays(Forms.Context))
{
if (await popupService.DisplayAlertAsync(
BusinessResources.GoToOverlayPermissionTitle,
BusinessResources.GoToOverlayPermissionMessage,
BusinessResources.Ok,
BusinessResources.Cancel))
{
var intent = new Intent(Android.Provider.Settings.ActionManageOverlayPermission,
Android.Net.Uri.Parse("package:" + Forms.Context.PackageName));
Forms.Context.StartActivity(intent);
}
}
}
然后,用户将被引导至设置以启用该功能。
关于c# - Android 10 Xamarin.Forms MainActivity 作为警报的全屏 Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62066811/