Android geocoder.getFromLocation函数抛出;等待服务器响应超时“;例外

Android geocoder.getFromLocation函数抛出;等待服务器响应超时“;例外,android,performance,Android,Performance,我试图通过从MainActivity启动IntentService来获取用户的位置。在服务中,我尝试在try块中对位置进行反向地理编码,但当我捕获异常并打印时,它会显示“在等待服务器响应时超时”异常。但有几次我得到了位置。因此我认为我的代码没有问题。但是如果它在10次中抛出8次异常,它将不会有用。因此,您可以建议一些方法来避免这种情况。以下是一个简单有效的解决方案: 创建以下两个函数: 与 我遭受了,并得到了错误,由于不可用的互联网连接 请检查是否已分配internet权限: <uses

我试图通过从MainActivity启动IntentService来获取用户的位置。在服务中,我尝试在try块中对位置进行反向地理编码,但当我捕获异常并打印时,它会显示“在等待服务器响应时超时”异常。但有几次我得到了位置。因此我认为我的代码没有问题。但是如果它在10次中抛出8次异常,它将不会有用。因此,您可以建议一些方法来避免这种情况。

以下是一个简单有效的解决方案:

创建以下两个函数: 与


我遭受了,并得到了错误,由于不可用的互联网连接

请检查是否已分配internet权限:

 <uses-permission android:name="android.permission.INTERNET" />

并再次检查您的互联网是否打开

为了得到响应,我在AsyncTask中编写代码,如下所示:

 class GeocodeAsyncTask extends AsyncTask<Void, Void, Address> {

        String errorMessage = "";

        @Override
        protected void onPreExecute() {

            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected Address doInBackground(Void ... none) {
            Geocoder geocoder = new Geocoder(DashboardActivity.this, Locale.getDefault());
            List<Address> addresses = null;


            double latitude = Double.parseDouble(strLatitude);
            double longitude = Double.parseDouble(strLongitude);

            try {
                addresses = geocoder.getFromLocation(latitude, longitude, 1);
            } catch (IOException ioException) {
                errorMessage = "Service Not Available";
                Log.e(TAG, errorMessage, ioException);
            } catch (IllegalArgumentException illegalArgumentException) {
                errorMessage = "Invalid Latitude or Longitude Used";
                Log.e(TAG, errorMessage + ". " +
                        "Latitude = " + latitude + ", Longitude = " +
                        longitude, illegalArgumentException);
            }


            if(addresses != null && addresses.size() > 0)
                return addresses.get(0);

            return null;
        }

        protected void onPostExecute(Address address) {
            if(address == null) {
                progressBar.setVisibility(View.INVISIBLE);

                tvcurrentLOc.setText(errorMessage);
            }
            else {
                String addressName = "";
                for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                    addressName += "," + address.getAddressLine(i);
                }
                progressBar.setVisibility(View.INVISIBLE);

                tvcurrentLOc.setText(addressName);
            }
        }
    }
类GeocodeAsyncTask扩展了AsyncTask{
字符串errorMessage=“”;
@凌驾
受保护的void onPreExecute(){
progressBar.setVisibility(View.VISIBLE);
}
@凌驾
受保护地址doInBackground(无效…无){
Geocoder Geocoder=新的Geocoder(DashboardActivity.this,Locale.getDefault());
列表地址=空;
双纬度=double.parseDouble(标准纬度);
双经度=double.parseDouble(标准经度);
试一试{
地址=地理编码器.getFromLocation(纬度,经度,1);
}捕获(IOException IOException){
errorMessage=“服务不可用”;
Log.e(标签、错误消息、ioException);
}捕获(IllegalArgumentException IllegalArgumentException){
errorMessage=“使用的纬度或经度无效”;
Log.e(标签,errorMessage+“)+
“纬度=”+纬度+”,经度=”+
经度,illegalArgumentException);
}
if(addresses!=null&&addresses.size()>0)
返回地址。获取(0);
返回null;
}
受保护的void onPostExecute(地址){
如果(地址==null){
progressBar.setVisibility(View.INVISIBLE);
tvcurrentLOc.setText(错误消息);
}
否则{
字符串addressName=“”;
对于(int i=0;i

希望能有所帮助。

这里是解决这个问题的快速方法

public class GPSL extends Service implements LocationListener {
public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    try
                    {
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("Network", "Network");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                    catch (SecurityException e)
                    {
                        e.printStackTrace();
                    }

                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        try
                        {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (locationManager != null) {
                                location = locationManager
                                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
                                }
                            }
                        }
                        catch (SecurityException e)
                        {
                            e.printStackTrace();
                        }

                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e("Gecoder", "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }

    /**
     * Try to get AddressLine
     * @return null or addressLine
     */
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    /**
     * Try to get Locality
     * @return null or locality
     */
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        }
        else {
            return null;
        }
    }
}
公共类GPSL扩展服务实现LocationListener{
公共位置getLocation(){
试一试{
locationManager=(locationManager)mContext
.getSystemService(位置服务);
//获取GPS状态
isGPSEnabled=位置管理器
.isprovidenabled(LocationManager.GPS\U提供商);
//获取网络状态
isNetworkEnabled=locationManager
.isProviderEnabled(LocationManager.NETWORK_提供商);
如果(!isGPSEnabled&!isNetworkEnabled){
//未启用任何网络提供程序
}否则{
this.canGetLocation=true;
//首先从网络提供商处获取位置
if(可联网){
尝试
{
locationManager.RequestLocationUpdate(
LocationManager.NETWORK\u提供程序,
最短时间更新,
最小距离\u更改\u用于更新,此);
Log.d(“网络”、“网络”);
如果(locationManager!=null){
位置=位置管理器
.getLastKnownLocation(LocationManager.网络提供商);
如果(位置!=null){
纬度=位置。getLatitude();
longitude=location.getLongitude();
}
}
}
捕获(安全异常e)
{
e、 printStackTrace();
}
}
//如果启用GPS,则使用GPS服务获取横向/纵向
如果(isGPSEnabled){
if(位置==null){
尝试
{
locationManager.RequestLocationUpdate(
LocationManager.GPS\u提供程序,
最短时间更新,
最小距离\u更改\u用于更新,此);
Log.d(“GPS启用”、“GPS启用”);
如果(locationManager!=null){
位置=位置管理器
.getLastKnownLocation(LocationManager.GPS\U提供商);
如果(位置!=null){
纬度=位置。getLatitude();
longitude=location.getLongitude();
}
}
}
捕获(安全异常e)
{
e、 printStackTrace();
}
}
}
}
}捕获(例外e){
e、 printStackTrace();
}
ret
 <uses-permission android:name="android.permission.INTERNET" />
 class GeocodeAsyncTask extends AsyncTask<Void, Void, Address> {

        String errorMessage = "";

        @Override
        protected void onPreExecute() {

            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected Address doInBackground(Void ... none) {
            Geocoder geocoder = new Geocoder(DashboardActivity.this, Locale.getDefault());
            List<Address> addresses = null;


            double latitude = Double.parseDouble(strLatitude);
            double longitude = Double.parseDouble(strLongitude);

            try {
                addresses = geocoder.getFromLocation(latitude, longitude, 1);
            } catch (IOException ioException) {
                errorMessage = "Service Not Available";
                Log.e(TAG, errorMessage, ioException);
            } catch (IllegalArgumentException illegalArgumentException) {
                errorMessage = "Invalid Latitude or Longitude Used";
                Log.e(TAG, errorMessage + ". " +
                        "Latitude = " + latitude + ", Longitude = " +
                        longitude, illegalArgumentException);
            }


            if(addresses != null && addresses.size() > 0)
                return addresses.get(0);

            return null;
        }

        protected void onPostExecute(Address address) {
            if(address == null) {
                progressBar.setVisibility(View.INVISIBLE);

                tvcurrentLOc.setText(errorMessage);
            }
            else {
                String addressName = "";
                for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                    addressName += "," + address.getAddressLine(i);
                }
                progressBar.setVisibility(View.INVISIBLE);

                tvcurrentLOc.setText(addressName);
            }
        }
    }
public class GPSL extends Service implements LocationListener {
public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    try
                    {
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("Network", "Network");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                    catch (SecurityException e)
                    {
                        e.printStackTrace();
                    }

                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        try
                        {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (locationManager != null) {
                                location = locationManager
                                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
                                }
                            }
                        }
                        catch (SecurityException e)
                        {
                            e.printStackTrace();
                        }

                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e("Gecoder", "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }

    /**
     * Try to get AddressLine
     * @return null or addressLine
     */
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    /**
     * Try to get Locality
     * @return null or locality
     */
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        }
        else {
            return null;
        }
    }
}