Friday, September 14, 2018

Backgrounding with Xamarin.Forms the Easy Way

Overview


Ever wonder how facebook and twitter apps process there background to fetch a new content? And it looks so slick that when you refresh it was snappy and smooth, Making the user believed that the content is refreshed and updated in a snap when in fact it was done in the background.

The secret behind it was the background service. And so we have created Matcha.BackgroundService to make our backgrounding task be simple and maintenable.

Background Service


Background Services are very commonly used for tasks that are performed in the background, such as downloading files, long calculations, playing music, and periodic method call. Each platform has a different way on enabling and registering the Background Service. 

If you want to dig deeper about advance Background Service per each platform you can check on this links below:

Android BackgroundServices LINK

iOS BackgroundServices LINK



Easy Backgrounding


If you want a simple backgrounding that behave like facebook or twitter apps in which periodically fetching a content at the background then this one is for you.



Matcha Background Service Plugin

Setup

  • NuGet: Matcha.BackgroundService NuGet
  • PM> Install-Package Matcha.BackgroundService
  • Install into ALL of your projects, include client projects.

For Android

You call the "Init" method before all libraries initialization in MainActivity class.
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
 {
     protected override void OnCreate(Bundle bundle)
     {
      BackgroundAggregator.Init(this);
      
      base.OnCreate(bundle);
         ....// Code for init was here
     }
 }

For iOS

You call the "Init" method before all libraries initialization in FinishedLaunching method in FormsApplicationDelegate class.
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        BackgroundAggregator.Init(this);
        
          ....// Code for init was here
        return base.FinishedLaunching(app, options);
    }
}

Create Periodic Task

You will have to inherit IPeriodicTask interface in which you will supply and implement the interval and StartJob, Periodic Task will be execute every interval once it is registered.
public class PeriodicWebCall : IPeriodicTask
{
    public PeriodicWebCallTest(int seconds)
    {
        Interval = TimeSpan.FromSeconds(seconds);
    }

    public TimeSpan Interval { get; set; }
    
    public Task StartJob()
    {
        // YOUR CODE HERE
        // THIS CODE WILL BE EXECUTE EVERY INTERVAL
    }
}

Register Periodic Task

After you have implemented the Periodic Task you will need to register it to Background Aggregator Service, We define it on OnStart() method under App.cs.
protected override void OnStart()
{
   //Register Periodic Tasks
   BackgroundAggregatorService.Add(() => new PeriodicWebCall(3));
   BackgroundAggregatorService.Add(() => new PeriodicCall2(4));

   //Start the background service
   BackgroundAggregatorService.StartBackgroundService();
}

Quirks and Limitation

Keep in mind that the plugin was not design to communicate with UI thread, one way of dealing the transfer of information is through storage (e.g. Sqlite or Settings plugin). Our sample project is using Monkey-Cache storage.
Starting with Android Oreo it has already introduced the background execution limits similar to iOS background time limits assuming the app is in background mode or app is closed or minimized, as discuss on this article.
For more info about Backgrounding in Android in iOS please check the link HERE.

That's it

You can now run your app that runs a Periodic Task every interval in the Background Service. We have provided a few good samples to for you to dig in.

Our Sample

We have created a sample app that has 3 Periodic Task in the background that gets an RSS feed from news outlet like BBC News, CNN News and Washington Post. It refreshes the data every 3 minutes.



Wrapping Up



If you have some questions go shoot me a message here and will gladly answer your questions. If you want more and advance topic you can catch us at this facebook groups MondPH And Xamdavao. If you want the full sample source you can check it right here LINK. enjoy coding.







2 comments:

  1. I need a service that keeps running even when the aplication is closed or if the phone restarts,restart the service, can it be done with this plugin?

    ReplyDelete
    Replies
    1. As discussed in "Quirks and Limitation" the background can still run at a limited time imposed by operating system. For more info about backgrounding please read "Quirks and Limitation" section of this article.

      Delete