Forum Xamarin.Android

How to tell if the user has turned on/off location services

sisaackssisaacks Member ✭✭✭

I am using Xamarin Essentials to tell if I have location permissions.
There is also Geolocation you can call to get Latitude and Altitude....if location services are not on.....it will tell you they are not eabled.
But is there away on Android to get notified when the user either turns on or off Location Services?
I have yet to find a good way to do this.

Best Answers

  • LeonLuLeonLu Member, Xamarin Team Xamurai
    Accepted Answer

    When I turn off location services....that method is called multiple times. When I turn location services back on, initially its >false...then becomes true, which displays an inaccurate toast message

    To fix this issue, you can add an GPSFlag to get the initialized flag in the MainActivity.cs .

     public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        {
            public static bool Gpsflag = false;
            protected override void OnCreate(Bundle savedInstanceState)
            {
                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;
    
                base.OnCreate(savedInstanceState);
    
                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
                global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
    
                LocationManager lm = (LocationManager)this.GetSystemService(Context.LocationService);
                Gpsflag = lm.IsProviderEnabled(LocationManager.GpsProvider);
    
                GpsLocationReceiver receiver = new GpsLocationReceiver();
                RegisterReceiver(receiver, new IntentFilter(LocationManager.ProvidersChangedAction));
    
                LoadApplication(new App());
    
            }
    

    When you get the broadcastReceiver, you can judge it. If get the same flags, the Toast will not be poped up.

     [BroadcastReceiver(Enabled = true, Exported = false)]
        [IntentFilter(new[] { LocationManager.ProvidersChangedAction })]
        public class GpsLocationReceiver : BroadcastReceiver
        {
            public override void OnReceive(Context context, Intent intent)
            {
    
                LocationManager lm = (LocationManager)context.GetSystemService(Context.LocationService);
                bool gps_enabled = false;
    
    
                try
                {
                    gps_enabled = lm.IsProviderEnabled(LocationManager.GpsProvider);
                }
                catch (Exception ex) { }
    
                if (intent.Action.Equals("android.location.PROVIDERS_CHANGED")&& (gps_enabled!=MainActivity.Gpsflag))
                {
    
                    Console.WriteLine("============"+ gps_enabled + "================");
                    Toast.MakeText(context, "in android.location.PROVIDERS_CHANGED status:"+ gps_enabled,
                    ToastLength.Short).Show();
                    MainActivity.Gpsflag = gps_enabled;
                }
            }
        }
    }
    

    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • LeonLuLeonLu Member, Xamarin Team Xamurai
    edited January 6 Accepted Answer

    For iOS, you can refer to this thread:https://docs.microsoft.com/en-us/answers/questions/170690/xamarin-forms-how-to-check-if-gps-is-on-or-off-in.html

    But On iOS, you only get to ask once. If the user denies the permission, you just have to bother them to go to the app settings and grant it there.

    If the reply is helpful, please do not forget to accept it as answer. it will help others who have similar issue.


    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

Answers

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    You can create a broadcastrecevier to achieve it.

     [BroadcastReceiver(Enabled = true, Exported = false)]
        [IntentFilter(new[] { LocationManager.ProvidersChangedAction })]
        public class GpsLocationReceiver : BroadcastReceiver
        {
            public override void OnReceive(Context context, Intent intent)
            {
                if (intent.Action.Equals("android.location.PROVIDERS_CHANGED"))
                {
                    LocationManager lm = (LocationManager)context.GetSystemService(Context.LocationService);
                    bool gps_enabled = false;
    
    
                    try
                    {
                        gps_enabled = lm.IsProviderEnabled(LocationManager.GpsProvider);
                    } catch (Exception ex) { }
    
                    Toast.MakeText(context, "in android.location.PROVIDERS_CHANGED status:"+ gps_enabled,
                    ToastLength.Short).Show();
    
                }
            }
        }
    

    Then register to the oncreate method.

     protected override void OnCreate(Bundle savedInstanceState)
            {
                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;
    
                base.OnCreate(savedInstanceState);
    
                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
                global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
                GpsLocationReceiver receiver = new GpsLocationReceiver();
                RegisterReceiver(receiver, new IntentFilter(LocationManager.ProvidersChangedAction));
    
    
                LoadApplication(new App());
    
            }
    

    Here is running screenshot.


    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • sisaackssisaacks Member ✭✭✭

    @LeonLu

    The first class you defined above, where does that go? In the main project or the anroid project? What is the "Toast" you have? Is that a plugin? Thank you for your assistance :)

  • sisaackssisaacks Member ✭✭✭

    @LeonLu Okay I implemented this...but it does not seem to work correctly. When I turn off location services....that method is called multiple times. When I turn location services back on, initially its false...then becomes true, which displays an inaccurate toast message

  • LeonLuLeonLu Member, Xamarin Team Xamurai
    Accepted Answer

    When I turn off location services....that method is called multiple times. When I turn location services back on, initially its >false...then becomes true, which displays an inaccurate toast message

    To fix this issue, you can add an GPSFlag to get the initialized flag in the MainActivity.cs .

     public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        {
            public static bool Gpsflag = false;
            protected override void OnCreate(Bundle savedInstanceState)
            {
                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;
    
                base.OnCreate(savedInstanceState);
    
                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
                global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
    
                LocationManager lm = (LocationManager)this.GetSystemService(Context.LocationService);
                Gpsflag = lm.IsProviderEnabled(LocationManager.GpsProvider);
    
                GpsLocationReceiver receiver = new GpsLocationReceiver();
                RegisterReceiver(receiver, new IntentFilter(LocationManager.ProvidersChangedAction));
    
                LoadApplication(new App());
    
            }
    

    When you get the broadcastReceiver, you can judge it. If get the same flags, the Toast will not be poped up.

     [BroadcastReceiver(Enabled = true, Exported = false)]
        [IntentFilter(new[] { LocationManager.ProvidersChangedAction })]
        public class GpsLocationReceiver : BroadcastReceiver
        {
            public override void OnReceive(Context context, Intent intent)
            {
    
                LocationManager lm = (LocationManager)context.GetSystemService(Context.LocationService);
                bool gps_enabled = false;
    
    
                try
                {
                    gps_enabled = lm.IsProviderEnabled(LocationManager.GpsProvider);
                }
                catch (Exception ex) { }
    
                if (intent.Action.Equals("android.location.PROVIDERS_CHANGED")&& (gps_enabled!=MainActivity.Gpsflag))
                {
    
                    Console.WriteLine("============"+ gps_enabled + "================");
                    Toast.MakeText(context, "in android.location.PROVIDERS_CHANGED status:"+ gps_enabled,
                    ToastLength.Short).Show();
                    MainActivity.Gpsflag = gps_enabled;
                }
            }
        }
    }
    

    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • sisaackssisaacks Member ✭✭✭

    Thank you thats what I ended up doing :) prior to reading this
    So....while I have your attention...is what is the trick with IOS?

  • LeonLuLeonLu Member, Xamarin Team Xamurai
    edited January 6 Accepted Answer

    For iOS, you can refer to this thread:https://docs.microsoft.com/en-us/answers/questions/170690/xamarin-forms-how-to-check-if-gps-is-on-or-off-in.html

    But On iOS, you only get to ask once. If the user denies the permission, you just have to bother them to go to the app settings and grant it there.

    If the reply is helpful, please do not forget to accept it as answer. it will help others who have similar issue.


    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • sisaackssisaacks Member ✭✭✭

    @LeonLu

    The example for IOS you sent, the bool status = CLLocationManager.LocationServicesEnabled; method call...does that go in the IOS project in a LocationShare like the Android?

  • sisaackssisaacks Member ✭✭✭

    @LeonLu

    One more question....the example you sent me...is how to find out if the services are enabled....but how can I be notified? For example, say I am doing an update via bluetooth and the user decides to turn of location services

  • sisaackssisaacks Member ✭✭✭

    @LeonLu

    Disregard My Last question...the first IOS question still stands

  • sisaackssisaacks Member ✭✭✭

    @LeonLu

    I guess what I am wanting to know is the following for IOS:
    The example for IOS you sent, the bool status = CLLocationManager.LocationServicesEnabled; method call...does that go in the IOS project in a LocationShare like the Android?

    Also how do I create a broadcaster to know when location services have been turned on or off in IOS??

    regards

  • sisaackssisaacks Member ✭✭✭

    @LeonLu curious if you can help me out....for IOS am using CLLocationManager.LocationServicesEnabled but it always returns true. I am not sure why.

    ///


    /// Will notify IOS that location services have turned off.
    ///

    ///


    [Export("applicationWillEnterForeground:")]
    public override void WillEnterForeground(UIApplication uiApplication)
    {
    if(!CLLocationManager.LocationServicesEnabled)
    {
    PopUpUtility.ShowPopUp("Location Services", "Location Services are required for communication via Bluetooth to exterior devices and device retrieval of altitude and latitude.");
            }
    
            base.WillEnterForeground(uiApplication);
        }  
    
Sign In or Register to comment.