2

I have a background service in android.

My code is as follows:

[Service]
public class PeriodicService : Service
{
    public override IBinder OnBind(Intent intent)
    {
        return null;
    }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        Device.StartTimer(TimeSpan.FromSeconds(5), () =>
             {
                 // code
              });
        return StartCommandResult.Sticky;
    }

}

The MainActivity class:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    global::Xamarin.Forms.Forms.Init(this, bundle);
    LoadApplication(new App());

    StartService(new Intent(this, typeof(PeriodicService)));
}

Permission AndroidManifest.xml:

<uses-permission android:name="android.permission.PeriodicService" />

The problem is that my service only works in the background when the app is active or in the foreground but when I close the app it doesn't run in the background.

Izaak van Dongen
  • 2,450
  • 13
  • 23
Mazen
  • 37
  • 1
  • 4
  • By background do you mean: 1) when the app is closed, 2) when the app is navigated away from? – MedievalCoder Jan 16 '20 at 21:42
  • 1
    by background I mean when the app is closed. i want to implement a service that runs permanently in the background. and the service should work when the app is closed or open – Mazen Jan 17 '20 at 10:09
  • @Mazen Hi, you can have a look at [Remote Processes](https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/out-of-process-services) in Android . It will remain running even when app is killed . – Junior Jiang Jan 20 '20 at 02:10
  • @JuniorJiang-MSFT do you have a code example – Mazen Jan 20 '20 at 14:33
  • @Mazen Sorry , I have no sample now . If have later will share here. – Junior Jiang Jan 21 '20 at 02:04

1 Answers1

2

A possible solution is to follow along with what Fabio has written in his post about how to create The Never Ending Background Task.

The idea behind this is to create a BroadcastReceiver and Android Service in the manifest. The BroadcastReceiver will then activate the service with foreground priority as the application is being closed. If you are dealing with post Android 7 then he created an update to his blog showing The Fix.

Just to get a better understanding of how basic Android services operate, I'd recommend taking a look at this Android Services Tutorial

I also saw this other StackOverflow post that seems to be pretty similar so maybe there will be some useful info over there too.

I'm not too acclimated in this stuff, but I was able to follow along with the blog posts pretty easily so I hope this ends up helping :). If anyone finds a better solution I'd love to hear about it so tag be (if you would be so kind) so I can stay updated!

MedievalCoder
  • 627
  • 7
  • 10