Search code examples
c#androidsqlitexamarinsqlite.net

Xamarin Service and Forms Init


I'm writing a Xamarin Android application that consists of service and a page for configuration. The service starts after device boot (launched by a BroadcastReceiver) and needs a database connection to read the configuration. I receive an error when the service tries to read the database:

You MUST call Xamarin.Forms.Init(); prior to using it.

For the database connection, I'm using SQLite.Net. I know that I need to call the Xamarin.Forms.Init() to use the database, but I don't know how I can do it. The Init() method needs context and Android.OS.Bundle as inputs, but in the BroadcastReceiver class, I have only the context. How I can retrieve the bundle? Is there another way to do that?

This is the exception stacktrace:

at Xamarin.Forms.Device.get_PlatformServices () 
  at Xamarin.Forms.Device.GetAssemblies () 
  at Xamarin.Forms.DependencyService.Initialize () 
  at Xamarin.Forms.DependencyService.Get[T] (Xamarin.Forms.DependencyFetchTarget fetchTarget) 
  at MyProject.Database.ConfigurationDBService..ctor () 
  at MyProject.Utils.ConfigurationUtils.getConfig () 
  at MyProject.InvoiceUploadService.OnStartCommand (Android.Content.Intent intent, Android.App.StartCommandFlags flags,System.Int32 startId)

Solution

  • I solved the problem by running the database connection without a DependecyService as suggested by SushiHangover in the question's comments.