Android: send local notification from background

I’m trying to implement custom call screen when app receive certain push notification.
When I have all the data avalable, I’m trying to raise local notification while app is still in background.

NB: it’s a .NET code for MAUI, but it’s basically a complete copycat of Android API, so should be readable for Java programmers.

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
}

Creating call notification right away not possible before any activity is attached, I cannot get PendingIntent (Attempt to invoke virtual method ‘android.os.UserHandle android.content.Context.getUser()’ on a null object reference) or feed builder with required resources (Attempt to invoke virtual method ‘android.content.res.Resources android.content.Context.getResources()’ on a null object reference / Java.Lang.NullPointerException: Attempt to invoke virtual method ‘android.os.UserHandle android.content.Context.getUser()’ on a null object reference )

The only solution I found is to create a Service:

[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;
}
}

When app is unloaded, all this work fine on Androids 11 and older, but since new restrictions of foreground services run, I get error on starting a service:

            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

Android.App.ForegroundServiceStartNotAllowedException:
startForegroundService() not allowed due to mAllowStartForeground
false

and

Android.App.BackgroundServiceStartNotAllowedException: Not allowed to
start service Intent { act=START_SERVICE
cmp=com.company.app/crc646332b1bcddc0e22c.DroidCallService
(has extras) }: app is in background

I saw multiple recommendations like asking user to skip battery optimization, using alarm clock or calendar etc, but it’s all like “quirky” solutions.

Task is simple: background instance needs to run a foreground service. What is the proper way to do it and how?

3

Apps that target Android 12 (API level 31) or higher can’t start foreground services while running in the background, except for a few special cases. If an app tries to start a foreground service while the app is running in the background, and the foreground service doesn’t satisfy one of the exceptional cases, the system throws a ForegroundServiceStartNotAllowedException.

Exemptions from background start restrictions:

  • Your app transitions from a user-visible state, such as an activity.
  • Your app can start an activity from the background, except for the
    case where the app has an activity in the back stack of an existing
    task.
  • Your app receives a high-priority message using Firebase Cloud
    Messaging.
  • The user performs an action on a UI element related to your app. For
    example, they might interact with a bubble, notification, widget, or
    activity.
  • Your app invokes an exact alarm to complete an action that the user
    requests.
  • Your app is the device’s current input method.
  • Your app receives an event that’s related to geofencing or activity
    recognition transition.
  • After the device reboots and receives the ACTION_BOOT_COMPLETED,
    ACTION_LOCKED_BOOT_COMPLETED, or ACTION_MY_PACKAGE_REPLACED intent
    action in a broadcast receiver.

For more information, please check: Restrictions on starting a foreground service from the background.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật