GeoCoder的getFromLocation方法可以引发NetworkOnMainThreadException吗? [英] Can GeoCoder getFromLocation method cause a NetworkOnMainThreadException to be thrown?

查看:88
本文介绍了GeoCoder的getFromLocation方法可以引发NetworkOnMainThreadException吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序经过了全面测试,并且可以在Android Gingerbread(和较旧的Android版本)上正常运行.我从用户报告的崩溃错误中注意到,运行更高版本的Android操作系统的手机正在抛出 NetworkOnMainThreadException .

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.

我正在尝试遍历我的代码并消除/修复所有肇事者.如果从主/用户界面线程调用 GeoCoder getFromLocation getFromLocationName 方法会抛出 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?

推荐答案

似乎类似于这些 Geocoder 方法和 any 调用将引发 NetworkOnMainThreadException .因此,如有疑问,请将其粘贴在单独的线程中!

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!

下面是一个如何从另一个线程调用 GeoCoder.getFromLocation()方法的示例:

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);

这篇关于GeoCoder的getFromLocation方法可以引发NetworkOnMainThreadException吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆