Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

android - Can GeoCoder getFromLocation method cause a NetworkOnMainThreadException to be thrown?

I have an app which was tested thoroughly and working fine on Android Gingerbread (and older Android versions). I've noticed from users' reported crash errors that phones running later versions of the Android operating system are throwing a NetworkOnMainThreadException.

I'm trying to work through my code and eliminate/fix all culprits. Would the GeoCoder getFromLocation and getFromLocationName methods throw a NetworkOnMainThreadException if called from the main/ui thread?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Seems like these Geocoder methods and any networking or i/o calls are going to throw up a NetworkOnMainThreadException. So, if in doubt, stick it in a separate thread!

Here's an example of how to call the GeoCoder.getFromLocation() method from another thread:

new AsyncTask<GeoPoint, Void, Address>()
{
  @Override
  protected Address doInBackground(GeoPoint... geoPoints)
  {
    try
    {
      Geocoder geoCoder = new Geocoder(context);
      double latitude = geoPoints[0].getLatitudeE6() / 1E6;
      double longitude = geoPoints[0].getLongitudeE6() / 1E6;
      List<Address> addresses = geoCoder.getFromLocation(latitude, longitude, 1);
      if (addresses.size() > 0)
        return addresses.get(0);
    }
    catch (IOException ex)
    {
      // log exception or do whatever you want to do with it!
    }
    return null;
  }

  @Override
  protected void onPostExecute(Address address)
  {
    // do whatever you want/need to do with the address found
    // remember to check first that it's not null
  }
}.execute(myGeoPoint);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...