0

I'm starting a LocationService in Xamarin forms during login. And this service runs for every 5 mins, fetches location and stores in local DB. For some unknown reason location service is not working after some hours.

Whenever the app is killed and opened, I'm checking to see if the service has stopped. If it is stopped I'm starting the service again as follows:

In OnStart and OnResume I'm checking for running service as follows:

bool IsLocationServiceRunning = DependencyService.Get<IServiceRunning>().IsServiceRunning();
if (!IsLocationServiceRunning)
                    DependencyService.Get<IDeviceService>().StartLocationService();

ServiceRunningInterface:

public bool IsServiceRunning()
    {
            ActivityManager manager = (ActivityManager)Forms.Context.GetSystemService(Context.ActivityService);
            Type serviceClass = typeof(LocationService);
            foreach (var service in manager.GetRunningServices(int.MaxValue))
            {
                if (service.Service.ClassName.EndsWith(typeof(LocationService).Name))
                {
                    return true;
                }
            }
        }
    return false;
}

Every time I will get Is LocationRunning as true (which is not) and service won't get started.

Sai Sunkari
  • 179
  • 3
  • 27
  • When I doing search, I find people say that `getRunningServices` has been deprecated since **Android O** and you should not rely on this Api to get RunningServices. See comments in these threads: [how-to-check-if-a-service-is-running-on-android-8-api-26](https://stackoverflow.com/questions/48506971/how-to-check-if-a-service-is-running-on-android-8-api-26), [service-on-android](https://stackoverflow.com/a/5921190/10539446). You could change another way to check if the service is running. – nevermore Jun 06 '19 at 08:33
  • @JackHua-MSFT thanks for the reply. Instead of above all these, I just want to stop the service and start new, I'm doing this by : Android.App.Application.Context.StopService(new Intent(Android.App.Application.Context, typeof(LocationService))); Does this work to stop this service? – Sai Sunkari Jun 06 '19 at 18:45
  • Check the [document here](https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/creating-a-service/started-services#stopping-the-service) about stopService. – nevermore Jun 10 '19 at 08:59

0 Answers0