Forum Xamarin.Android

Current Device Location

mnayyermnayyer PKMember ✭✭

Following this link.
https://developer.xamarin.com/recipes/android/os_device_resources/gps/get_current_device_location/

get exception provider does not exist at this line
_locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);

Best Answer

  • mnayyermnayyer PK ✭✭
    Accepted Answer

    @AnbuVijay27

    c-sharpcorner.com/article/xamarin-android-create-android-gps-current-location-app/

    it worked for me now.. The problem was with my phone location access.

Answers

  • Hardik_MistryHardik_Mistry USMember, University ✭✭✭

    @mnayyer

    Can you verify you had set appropriate permission in AndroidManifest.xml ?, the document suggests to set permission via C# (the details are in the beginning of the documentation)

    Also can you refactor the OnResume method as illustrated?

    protected override void OnResume()
    {
        base.OnResume();
    
        try
        {
            _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
        }
        catch(Exception ex)
        {
            Log.Error("OnResume", ex.StackTrace); // you will see the information in Output window (bottom of VS)
        }
    }
    

    This shall hopefully give some more information as what might be going wrong.

    Try and share your feedback.

  • mnayyermnayyer PKMember ✭✭
    edited May 2017

    @HardikAnantMistry
    This is what I've found in output window ...

  • Hardik_MistryHardik_Mistry USMember, University ✭✭✭

    @mnayyer

    Will it be possible to paste ex.StackTrace information?

    While you debug, when that yellow indicator (execution point) is in the catch block, if you hover onto ex as object name, you can see variety of properties, one of them will be StackTrace, hover your mouse onto StackTrace property, and copy the content and paste the same here.

  • mnayyermnayyer PKMember ✭✭

    @HardikAnantMistry

    " at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143 \n at Java.Interop.JniEnvironment+InstanceMethods.CallVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00084] in /Users/builder/data/lanes/4468/b16fb820/source/Java.Interop/src/Java.Interop/Java.Interop/JniEnvironment.g.cs:11643 \n at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x00031] in /Users/builder/data/lanes/4468/b16fb820/source/Java.Interop/src/Java.Interop/Java.Interop/JniPeerMembers.JniInstanceMethods_Invoke.cs:26 \n at Android.Locations.LocationManager.RequestLocationUpdates (System.String provider, System.Int64 minTime, System.Single minDistance, Android.Locations.ILocationListener listener) [0x00077] in /Users/builder/data/lanes/4468/b16fb820/source/monodroid/src/Mono.Android/platforms/android-25/src/generated/Android.Locations.LocationManager.cs:1122 \n at QuickBoo.MainActivity.OnResume () [0x00009] in E:\App Codes\QB 2\QuickBoo\MainActivity.cs:362 \n --- End of managed Java.Lang.IllegalArgumentException stack trace ---\njava.lang.IllegalArgumentException: provider doesn't exist: \n\tat android.os.Parcel.readException(Parcel.java:1603)\n\tat android.os.Parcel.readException(Parcel.java:1552)\n\tat android.location.ILocationManager$Stub$Proxy.requestLocationUpdates(ILocationManager.java:606)\n\tat android.location.LocationManager.requestLocationUpdates(LocationManager.java:885)\n\tat android.location.LocationManager.requestLocationUpdates(LocationManager.java:469)\n\tat md57bc138c4033815d0367fda09a4d76ceb.MainActivity.n_onResume(Native Method)\n\tat md57bc138c4033815d0367fda09a4d76ceb.MainActivity.onResume(MainActivity.java:91)\n\tat android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1268)\n\tat android.app.Activity.performResume(Activity.java:6443)\n\tat android.app.ActivityThread.performResumeActivity(ActivityThread.java:3299)\n\tat android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3345)\n\tat android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2659)\n\tat android.app.ActivityThread.-wrap11(ActivityThread.java)\n\tat android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)\n\tat android.os.Handler.dispatchMessage(Handler.java:111)\n\tat android.os.Looper.loop(Looper.java:207)\n\tat android.app.ActivityThread.main(ActivityThread.java:5728)\n\tat java.lang.reflect.Method.invoke(Native Method)\n\tat com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)\n\tat com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)\n"

  • mnayyermnayyer PKMember ✭✭

    @HardikAnantMistry
    this is my assembly

    and this is manifestFile

  • Hardik_MistryHardik_Mistry USMember, University ✭✭✭

    @mnayyer

    • Are you trying to the run the application on an emulator?
    • Can you post what is ex.Message property value?
    • Can you check Google APIs version on your emulator or device

      • It is possible, Google API might be missing and hence not behaving appropriately
    • Also can you verify if your app has permission from Settings > Apps > NameOfApp on the emulator or device, thing is if you are running the app on API 23 or higher, the permissions need to be handled on runtime and not when installing the app

    Suggested reference:

    Try and share your feedback.

  • mnayyermnayyer PKMember ✭✭
    edited May 2017

    @HardikAnantMistry
    I'm deploying it on mobile, having android marshmallow api 23

  • mnayyermnayyer PKMember ✭✭
    edited May 2017

    @AnbuVijay27
    After Following your link.
    I've debugged my code. So,
    var acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true); is returning 0. while calling InitializeLocationManager()

  • mnayyermnayyer PKMember ✭✭

    @AnbuVijay27
    PLz help.

  • mnayyermnayyer PKMember ✭✭
    @AnbuVijay27
    Still waiting for your reply !!!
  • AnbuMani27AnbuMani27 USMember ✭✭✭

    Hi @mnayyer .. please send your Androidmanifest.xml code

  • mnayyermnayyer PKMember ✭✭
    edited May 2017

    @AnbuVijay27
    Here it is.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="QuickBoo.QuickBoo" android:installLocation="auto">
        <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="25" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_GPS" />
        <application android:label="QuickBoo" android:icon="@drawable/Icon" android.Theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"></application>
    </manifest>
    
  • AnbuMani27AnbuMani27 USMember ✭✭✭

    @mnayyer this code its fine...

    Send u r Activity and InitializeLocationManager() code :smile:

  • mnayyermnayyer PKMember ✭✭
    edited May 2017

    @AnbuVijay27
    Here it is.

    [Activity(Label = "QuickBoo", Theme = "@style/MyTheme")]
        public class MainActivity : ActionBarActivity, ILocationListener
        {
            static readonly string TAG = "X:" + typeof(MainActivity).Name;
            Location _currentLocation;
            LocationManager _locationManager;
            string _locationProvider;
            TextView _locationText;
            private TextView _addressText;
        ....
        .........
            protected override void OnCreate(Bundle bundle)
                {
                base.OnCreate(bundle);
                        SetContentView(Resource.Layout.Main);
                ....
                .........
                InitializeLocationManager();
                ....
                }   
    
            private void InitializeLocationManager()
            {
                 _locationManager = (LocationManager)GetSystemService(LocationService);
                    var criteriaForLocationService = new Criteria
                    {
                        Accuracy = Accuracy.Coarse
                    };
                    var acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
    
                    if (acceptableLocationProviders.Any())
                    {
                        _locationProvider = acceptableLocationProviders.First();
                    }
                    else
                {
                    _locationProvider = string.Empty;
                    }
                    Log.Debug(TAG, "Using " + _locationProvider + ".");
            }
    ...
    .....
        protected override void OnResume()
            {
                base.OnResume();
                    try
                 {
                         _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
                }
                    catch (Exception ex)
                {
                        Log.Error("OnResume", ex.StackTrace); // you will see the information in Output window (bottom of VS)
                    }
            }
    
            protected override void OnPause()
             {
                    base.OnPause();
                    _locationManager.RemoveUpdates(this);
            }
    
            public void OnLocationChanged(Location location)
            {
                    _currentLocation = location;
                    if (_currentLocation == null)
                 {
                        _addressText.Text = "Unable to determine your location. Try again in a short while.";
                 }
                    else
                    {
                        _addressText.Text = string.Format("{0:f6},{1:f6}", _currentLocation.Latitude, _currentLocation.Longitude);
                    }
            }
    
            public void OnProviderDisabled(string provider)
            {
            }
    
            public void OnProviderEnabled(string provider)
            {
    
            }
    
            public void OnStatusChanged(string provider, [GeneratedEnum] Availability status, Bundle extras)
            {
        }
    }
    
  • AnbuMani27AnbuMani27 USMember ✭✭✭

    Hi @mnayyer try another way

      public class LocationActivity : AppCompatActivity, GoogleApiClient.IConnectionCallbacks,
            GoogleApiClient.IOnConnectionFailedListener, Android.Gms.Location.ILocationListener 
        {
    
    
            TextView txtlatitu;
            TextView txtlong; 
            LocationRequest locRequest;
            GoogleApiClient apiClient;
            bool _isGooglePlayServicesInstalled; 
    
            public string TAG { get; private set; } 
    
    
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
    
                // Create your application here
                SetContentView(Resource.Layout.Location);
    
    
    
                txtlatitu = FindViewById<TextView>(Resource.Id.TxtCurrentLatitude);
                txtlong = FindViewById<TextView>(Resource.Id.TxtCurrentLongitude);
    
                _isGooglePlayServicesInstalled = IsGooglePlayServicesInstalled();
    
                if (_isGooglePlayServicesInstalled)
                {
                    // pass in the Context, ConnectionListener and ConnectionFailedListener
                    apiClient = new GoogleApiClient.Builder(this, this, this)
                        .AddApi(LocationServices.API).Build();
    
                    // generate a location request that we will pass into a call for location updates
                    locRequest = new LocationRequest();
    
    
                }
                else
                {
                    Log.Error("Activity", "Google Play Services is not installed");
    
                    Finish();
                }
    
    
            }
    
            bool IsGooglePlayServicesInstalled()
            {
                //int queryResult = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this);
    
                //int queryResult = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this);
    
                int queryResult = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this.ApplicationContext);
    
                if (queryResult == ConnectionResult.Success)
                {
                    Log.Info(" ", "Google Play Services is installed on this device.");
                    return true;
                }
    
                if (queryResult == ConnectionResult.ServiceVersionUpdateRequired)
                {
                    //string errorString = GoogleApiAvailability.Instance.GetErrorString(queryResult);
                    //Log.Error("SplashScreenActivity", "There is a problem with Google Play Services on this device: {0} - {1}", queryResult, errorString);
                    Toast.MakeText(this, "please udpate your google play service", ToastLength.Long).Show();
                    // Show error dialog to let user debug google play services
                }
                else if (queryResult == ConnectionResult.ServiceMissing)
                {
    
                    Toast.MakeText(this, "Not Install google play service", ToastLength.Long).Show();
    
                }
                return false;
            }
            protected override void OnResume()
            {
                base.OnResume();
                Log.Debug("OnResume", "OnResume called, connecting to client...");
                apiClient.Connect();
    
            }
            protected override async void OnPause()
            {
                base.OnPause();
                Log.Debug("OnPause", "OnPause called, stopping location updates");
    
                if (apiClient.IsConnected)
                {
                    // stop location updates, passing in the LocationListener
                    await LocationServices.FusedLocationApi.RemoveLocationUpdates(apiClient, this);
    
                    apiClient.Disconnect();
                }
            } 
    
            public async void OnConnected(Bundle connectionHint)
            {
                Log.Info("LocationClient", "Now connected to client");
    
                if (apiClient.IsConnected)
                {
                    Android.Net.ConnectivityManager connectivityManager =     (Android.Net.ConnectivityManager)GetSystemService(ConnectivityService);
                    Android.Net.NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
                    bool isOnline = (activeConnection != null) && activeConnection.IsConnected;
                    if (isOnline == false)
                    {
                        var errorMessage = "Network Connection Failed";
                        Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                        builder.SetTitle("Result");
                        builder.SetMessage(errorMessage);
                        builder.SetCancelable(false);
                        builder.SetNegativeButton("OK", (EventHandler<DialogClickEventArgs>)null);
                        builder.Show();
    
                    }
                    else
                    {
    
                        LocationManager mlocManager = (LocationManager)GetSystemService(LocationService); ;
                        bool enabled = mlocManager.IsProviderEnabled(LocationManager.GpsProvider);
                        if (enabled == false)
                        {
                            var errorMessage = "This app wants to change your device settings ";
                            Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                            builder.SetTitle("Result");
                            builder.SetMessage(errorMessage);
                            builder.SetCancelable(false);
    
    
                            builder.SetNegativeButton("OK", (senderAlert, args) =>
                            {
                                StartActivity(new Intent(Android.Provider.Settings.ActionLocationSourceSettings));
                            });
                            Dialog dia = builder.Create();
                            builder.Show();
    
                        }
                        else
                        {
    
                            // Setting location priority to PRIORITY_HIGH_ACCURACY (100)
                            locRequest.SetPriority(100); 
                            // once a minute, you _must_ also change the FastestInterval to be less than or equal to your Interval
                            locRequest.SetFastestInterval(500);
                            locRequest.SetInterval(1000);
                            Log.Debug("LocationRequest", "Request priority set to status code {0}, interval set to {1} ms",
                                locRequest.Priority.ToString(), locRequest.Interval.ToString());
                            // pass in a location request and LocationListener
                            await LocationServices.FusedLocationApi.RequestLocationUpdates(apiClient, locRequest, this);
                            // In OnLocationChanged (below), we will make calls to update the UI
                        }
                    }
    
                }
                else
                {
                    Log.Info("LocationClient", "Please wait for Client to connect");
                }
    
            }
    
            public void OnDisconnected()
            {
                Log.Info("LocationClient", "Now disconnected from client");
            }
    
    
            public void OnLocationChanged(Android.Locations.Location location)
            {
                Log.Debug("LocationClient", "Location updated");
    
                    txtlatitu.Text = location.Latitude.ToString();
                    txtlong.Text = location.Longitude.ToString();
    
    
            }
    
            public void OnConnectionSuspended(int cause)
            {
    
            }
            public void OnConnectionFailed(ConnectionResult result)
            {
                Log.Info("LocationClient", "Connection failed, attempting to reach google play services");
            }
    
  • mnayyermnayyer PKMember ✭✭
    Accepted Answer

    @AnbuVijay27

    c-sharpcorner.com/article/xamarin-android-create-android-gps-current-location-app/

    it worked for me now.. The problem was with my phone location access.

  • AnbuMani27AnbuMani27 USMember ✭✭✭

    Hi @mnayyer Some country not working for first solutions, That's only i give another solution for get the location

  • chetanpskumarchetanpskumar USMember
    edited July 2017

    working fine ...Thank u @AnbuVijay27

Sign In or Register to comment.