Mazen
Mazen

Reputation: 37

Background Service in Xamarin.Forms, iOS, Android

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.

Upvotes: 2

Views: 3742

Answers (1)

MedievalCoder
MedievalCoder

Reputation: 657

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!

Upvotes: 2

Related Questions