0

I am trying to find if the location is from mock provider as shown below

  Location location = locationResult.getLastLocation();
  if (android.os.Build.VERSION.SDK_INT <= 30)
     allLocationData.put("isMock", location.isFromMockProvider());
  else if(android.os.Build.VERSION.SDK_INT >= 31)
     allLocationData.put("isMock", location.isMock());

Handling mock location is different in Api <= 30 and Api >= 31. Hence, isMock() to be used for Api >= 30. But When I ran above code getting following error

  error: cannot find symbol allLocationData.put("isMock", location.isMock());
                                                              ^
  symbol:   method isMock()
  location: variable location of type Location

Am I missing any import statements here?

4

1 回答 1

1

Either the isFromMockProvider() or the isMock() methods on the Location class will always throw an error here since only one of those methods can be present based on the API version of the Android device.

So we need to dynamically invoke the corresponding method in this scenario. And Reflection API is a way to go.

Your code can be changed as below using Reflection to dynamically invoke the method.

String methodName = "";
Boolean isMock = false;
Location location = locationResult.getLastLocation();
**//Determine the method name to be invoked**
if (android.os.Build.VERSION.SDK_INT <= 30) {
    methodName = "isFromMockProvider";
} else if(android.os.Build.VERSION.SDK_INT >= 31) {
        methodName = "isMock";
}
     
**//Invoke the method dynamically using Reflection**
Class<? extends Location> cls = location.getClass();
try {
    Method decMethod = cls.getDeclaredMethod(methodName);
    isMock = (Boolean) decMethod.invoke(location);
} catch (Exception e) {
    //Handle exception
}
            
**//Store the result finally**
allLocationData.put("isMock", isMock);
于 2021-08-18T17:20:33.293 回答