Location Method Calls Crashes On Some Devices
Solution 1:
That's because LocationManager.getLastKnownLocation() can return null.
In your code, you requested GPS provider to update your deivce's location. But when device's GPS is off, that method return null.
And if any requests hasn't been processed through LocationManager, LocationManager.getLastKnownLocation() return null value as well. Because LocationManager doesn't have a "Last Known Locations" value.
(You can check LocationManager's state with following adb command)
$adb shell dumpsys location
Therefore, if you want to get success with your code snippet, your device's GPS is ON and LocationManager has a "Last Known Locations"
Well, I use LocationManager.getLastKnownLocation() method as well, but slightly different .
I just check if there is any "Last Known Locations" value with LocationManager.getLastKnownLocation() method. Because that is fastest way to resolve current location value. However, If it return null, then request location update through requestLocationUpdates.
Locationlocation= lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
// request location update!!
lm.requestLocationUpdates (LocationManager.GPS_PROVIDER, 0, 0, listener);
}
There is also some technic resolve device's location, I think that's gonna be huge answer. Instead, I will link this video which is great explanation about location. (and other more tips!!)
Solution 2:
If it hasn't had a fix at all, then after the line
Locationlocation= lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location will be null. Therefore you need to cope with this by enclosing code that requires a location with
if (location != null){
// your code
}
Solution 3:
or try this
privateclassJavaScriptInterface { // use in javascript publicdoublegetLatitude() {
try{
return mostRecentLocation.getLatitude();
}catch(Exception e){ //some devive without last locationreturn25.046254;//default set Taipei Train Station (City Land Mark)
}
}
publicdoublegetLongitude() {
try{
return mostRecentLocation.getLongitude();
}catch(Exception e){ //some devive without last locationreturn121.51752;//default set Taipei Train Station (City Land Mark)
}
}
}
Post a Comment for "Location Method Calls Crashes On Some Devices"