Starting an android Service from Xamarin forms
android, c#, xamarin.forms
Solution
I think the problem is that you need to decorate the service class with:-
[Service (Label = "AndroidBatteryService", Icon = "@drawable/Icon") ]
This causes Xamarin to put the following into the generated AndroidManifest.xml file during the build (you can find this in the \obj\Debug\android directory)
<service android:icon="@drawable/icon" android:label="AndroidBatteryService" android:name="md55...1a.AndroidBatteryService" />
I used a very similar piece of code in my app and it worked fine. (Although you've probably worked this out by now.)
Problem
In Visual Studio I created a new class library (Xamarin Forms) :- Xamarin class library Here I added my service and gave it the most basic implementation possible for a started service (note - not a bound service. Expecting - toasts to be displayed when the application is started / stopped :- ``` namespace AndroidBatteryService { public class AndroidBatteryService : Service { public AndroidBatteryService() { } [return: GeneratedEnum] public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { Toast.MakeText(this, "The Battery Service was just started", ToastLength.Long).Show(); return base.OnStartCommand(intent, flags, startId); } public override void OnCreate() { base.OnCreate(); } public override void OnDestroy() { base.OnDestroy(); Toast.MakeText(this, "The Battery Service has been stopped", ToastLength.Long).Show(); } public override IBinder OnBind(Intent intent) { //started service, NOT a binded service - return null... return null; } } } ``` In another project I am invoking this service my running the following code :- ``` public void StartBatteryService() { Intent intent = new Intent(Android.App.Application.Context, typeof(AndroidBatteryService.AndroidBatteryService)); Android.App.Application.Context.StartService(intent); } ``` The code runs (I can step over it), but the OnStartCommand method in the actual service is not run and I am expecting it to. Any ideas??