问题
I had written a simple Activity to test presence of Geocoder, calling Geocoder.isPresent() always returns false.
Class:
public class LocationTestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Log.d( "LocationTestActivity", "Geocoder.isPresent : " + Geocoder.isPresent() );
}
}
AndroidManifest.xml ALSO has following entries before "application" element:
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Environment : Eclipse Indigo 3.7.1, ICS 4.0 emulator on XP Professional 2002 SP 3
Please help me understand:
1. Why Geocoder.isPresent() is always returing false?
2. What changes to make so that Geocoder.isPresent() returns true?
Thanks much in advance!
回答1:
Actually the Geocoder need a Service running in the background by the framework.
From the documentation:
The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists.
so if we look at the documentation of isPresent(), it states.
Returns true if the Geocoder methods getFromLocation and getFromLocationName are implemented. Lack of network connectivity may still cause these methods to return null or empty lists.
Note: keep in mind that isPresent()
is not available in Pre-Api 9 plateforms.
回答2:
Testing this code in Emulator or device ? I have faced same problem when I was using GeoCoder on 2.2 emulator. But code works fine on 2.1 emulator. Try to use 2.1
And code must be running fine on device.
回答3:
Use AsyncTask
to fetch coordinates from server using geocoder
. For example, getFromLocationName()
should be called using AsyncTask
. UI thread (main activity) does not allow the tasks which take too much time, hence the method returns empty list.
来源:https://stackoverflow.com/questions/9075446/geocoders-ispresent-method-always-returns-false