Calling Foreground service from Broadcast Receiver when app was closed / killed

Aravapalli Manikishore 21 Reputation points
2021-03-18T06:20:44.757+00:00

Hi Everyone,

I've problem in calling the Foreground Service from the Broadcast Receiver when the app was killed by user. It is working fine when the app is open or recent apps.

Actually, my requirement is to track the location for every X minutes even the app is killed / closed.
So, I created a Broadcast Receiver for Location service. And It is not working in Android 7 when the app got killed.
So, I created a Repeating Alarm and calling foreground service from alarm Receiver. It is working fine when the app is open. But not when app got killed.

I make the Alarm Receiver as

    <receiver android:process=":remote" android:name="ScheduledAlarmHandler"></receiver>

to run process even app got killed

Code to Alarm Receiver

   public async override void OnReceive(Context context, Intent intent)
    { 
        if (Build.VERSION.SdkInt < BuildVersionCodes.O)
        {
            if (ActivityCompat.CheckSelfPermission(context, Android.Manifest.Permission.AccessFineLocation) == Android.Content.PM.Permission.Granted)
            {
                var msg = new StartServiceMessage();
                Xamarin.Forms.MessagingCenter.Send<StartServiceMessage>(msg, "ServiceStarted");
            }
        }
 }

Can anyone help me with right approach.

Thanks in Advance.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,325 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JessieZhang-MSFT 7,706 Reputation points Microsoft Vendor
    2021-03-18T09:18:26.227+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    You can try to restarted the service once it been finished by a BroadcastReceiver .
    The function of BroadcastReceiver is to receive a signal when someone or something kills the service; its role is to restart the service.

    For more details, you can check:
    https://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android
    Though it's Java code, it's easy to understand and convert.

    Best Regards,

    Jessie Zhang

    ---
    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments