Когда у меня есть все доступные данные, я пытаюсь вызвать локальное уведомление, пока приложение все еще находится в фоновом режиме.
Примечание: это код .NET для MAUI, но по сути это полная копия Android API, поэтому он должен быть удобочитаемым для Java-программистов.
Код: Выделить всё
void RegisterNotification(string cid, string title){
.......
var clickIntent = new Intent(context, typeof(MainActivity));
clickIntent.AddFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop);
clickIntent.PutExtra("field1thatneeded", "abcde");
var pendingIntentFlags = (Build.VERSION.SdkInt >= BuildVersionCodes.S) ? PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable : PendingIntentFlags.UpdateCurrent;
var pendingIntent = PendingIntent.GetActivity(context, activityId, clickIntent, pendingIntentFlags);
.......
var notificationBuilder = new Notification.Builder(this, AppConstants.CallChannelID)
.SetAutoCancel(false)
.SetOngoing(true)
.SetContentTitle("Incoming call")
.SetContentText(title)
.SetContentIntent(pendingIntent)
.SetStyle(Notification.CallStyle.ForIncomingCall(incomingCaller, rejectPendingIntent, answerPendingIntent))
.SetCategory(Notification.CategoryCall);
var notification =notificationBuilder.Build();
#if ANDROID29_0_OR_GREATER
StartForeground(notificationID, notification, Android.Content.PM.ForegroundService.TypePhoneCall);
#else
StartForeground(notificationID, notification );
#endif
}
Единственное решение, которое я нашел, — это создать Сервис:
Код: Выделить всё
[Service(ForegroundServiceType = Android.Content.PM.ForegroundService.TypePhoneCall, Exported = false)] //this attribute fills up AndroidManifest
internal class DroidCallService: Service
{
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
if (intent.Action == "START_SERVICE")
{
var callID = intent.GetStringExtra("call_id");
var name = intent.GetStringExtra("call_title");
RegisterNotification(callID, name);
}
else if (intent.Action == "STOP_SERVICE")
{
StopForeground(StopForegroundFlags.Remove);
StopSelfResult(startId);
}
return StartCommandResult.NotSticky;
}
}
Код: Выделить всё
Intent startService = new Intent(ctx, typeof(DroidCallService));
startService.SetAction("START_SERVICE");
startService.PutExtra("call_id", callID);
startService.PutExtra("call_title", name);
#if ANDROID26_0_OR_GREATER
ctx.StartForegroundService(startService); // ERROR!
#else
ctx.StartService(startService);
#endif
startForegroundService() не разрешен из-за mAllowStartForeground
false
< /blockquote>
и
Android.App.BackgroundServiceStartNotAllowedException: невозможно
запустить службу Intent { act=START_SERVICEcmp=com.company.app/crc646332b1bcddc0e22c.DroidCallService
(есть дополнительные функции) }: приложение работает в фоновом режиме
Я видел несколько рекомендации, например, попросить пользователя пропустить оптимизацию батареи, использовать будильник или календарь и т. д., но все это похоже на «причудливые» решения.
Задача проста: фоновому экземпляру необходимо запустить службу приоритетного плана. Как правильно это сделать и как?
Подробнее здесь: https://stackoverflow.com/questions/789 ... background
Мобильная версия