Using AndroidJavaObject to get Location

On my Android I am trying to get access to the Location object through the Android sdk.

However, I am getting the error “no such static method with name='getLastKnownLocation”

Does anyone seen anything wrong with this code?

    using (var locationManager = new AndroidJavaClass("android.location.LocationManager"))
            {
                AndroidJavaObject locationObj = locationManager.Call<AndroidJavaObject>("getLastKnownLocation", "gps");
                if (locationObj != null)
                {
                    double latitude = locationObj.Call<double>("getLatitude");
                    double longitude = locationObj.Call<double>("getLongitude");
                    isMock = locationObj.Call<bool>("isFromMockProvider");
               }
         }

Well, you don’t have an instance of the LocationManager and getLastKnownLocation is an instance method of that class. You only get your hand on the class but not on an actual instance. As you can read in the docs an instance of that class can’t be created manually but has to be aquired through

Context.getSystemService(Context.LOCATION_SERVICE)

getSystemService is also an instance method of the Context class. To get the context of your Unity app you usually use:

using(var unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
using(var context = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity"))

With the context you should be able to call “getSystemService” with the string parameter “location”

using(var unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
using(var context = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity"))
using(var locationManager = context.Call<AndroidJavaObject>("getSystemService", "location"))
using(var locationObj = locationManager.Call<AndroidJavaObject>("getLastKnownLocation", "gps"))
{
    if (locationObj != null)
    {
        double latitude = locationObj.Call<double>("getLatitude");
        double longitude = locationObj.Call<double>("getLongitude");
        isMock = locationObj.Call<bool>("isFromMockProvider");
    }
}

Haven’t tested it but it should work as long as you have the “ACCESS_FINE_LOCATION” permission, the device has a GPS provider and that provider is enabled.

Though i’m wondering why you don’t just use Unity’s LocationService API?