调用 geoCoder.getFromLocation() 时服务不可用

Posted

技术标签:

【中文标题】调用 geoCoder.getFromLocation() 时服务不可用【英文标题】:Service not available while calling geoCoder.getFromLocation() 【发布时间】:2013-02-13 04:01:41 【问题描述】:

我知道有时 google 后端服务可能不可用。

因此一个解决方案可能是循环直到我得到数据。

private class getLocationDetails extends AsyncTask<String, Void, String> 

    @Override
    protected String doInBackground(String... params) 

        Log.d("looping", "" + count + "");
        count++;
        double lat = Double.parseDouble(params[0]);
        double lng = Double.parseDouble(params[1]);
        List<Address> addresses = null;
        try 

            Geocoder gCoder = new Geocoder(ImageAndLocationActivity.this,
                    Locale.getDefault());
            addresses = gCoder.getFromLocation(lat, lng, 1);
            Address addr = addresses.get(0);
            user_country = addr.getCountryName();
            user_city = addr.getLocality();
            user_district = addr.getSubAdminArea();

            if (user_city == null) 

                user_city = user_district;
            
         catch (Exception e) 

            Log.e("Exception in getLocationDetails - ", e.getMessage());
            return null;
        

        return "";
    

    @Override
    protected void onPostExecute(String result) 

        if (result != null) 

            Log.d("user_city = ", "" + user_city);
         else 

            new getLocationDetails().execute(CurrentLat + "", CurrentLng
                    + "");
        
    

    @Override
    protected void onPreExecute() 

    

    @Override
    protected void onProgressUpdate(Void... values) 

    

但我根本无法获得位置:

LogCat:

02-27 16:29:49.568: D/looping(10966): 110355
02-27 16:29:49.568: E/Exception in getLocationDetails -(10966): Service not Available
02-27 16:29:49.573: D/looping(10966): 110356
02-27 16:29:49.573: E/Exception in getLocationDetails -(10966): Service not Available
02-27 16:29:49.573: D/looping(10966): 110357
02-27 16:29:49.573: E/Exception in getLocationDetails -(10966): Service not Available

当然我已经添加了所有需要的权限:

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

我正在 三星 Galaxy Note GT-N7000(4.0.4 版)上尝试此功能

我是否缺少任何设置?与设备或应用程序有关?或者这通常会发生?如果是这样有更好的解决方案来解决这个问题吗??

谢谢

【问题讨论】:

没有。我已经看到中断了几分钟。尝试重新启动您的设备? isPresent() 总是返回True。然而它说Service not available。但是重新启动设备后,它工作正常。诡异的。用户怎么会知道:( 有没有比重启更好的解决方案?我有同样的问题。在测试中,我们在两部手机上都遇到了这个问题,并且重新启动解决了这个问题。我不认为让用户重启他们的手机是一个很好的解决方案。是否有其他对象可以替代 GeoCoder 对象? @JohnathanKong 使用这个http://maps.google.com/maps/api/geocode/json?address=" + address + "&amp;ka&amp;sensor=false 作为后备 【参考方案1】:

Geocoder 不起作用的实际原因是NetworkLocator 在行动中被杀死。可能是由于内存较少,或者您使用任务管理器杀死了所有服务?

我不确定,但这是一个猜测。我以前见过这个。去年我写了一个重新连接机制来加载 NetworkLocator.apk 并绑定到GeocoderService。我认为此更改尚未合并到 JellyBean 中,因此此问题仍然存在。

只能通过重启解决。 (NetworkLocationService 在启动时加载)

编辑:您不会在 JBP 或 KK 中看到此问题,此服务已移至 playstore 应用程序中。

【讨论】:

很好。但我检查了其他与地图相关的应用程序,如 MapsLocal..etc,它们都运行良好。可能是因为我使用的是基本的android.location.Geocoder 而他们可能使用的是some google service libraries??如果是这种情况,我刚开始使用google-play-services.jar 是否支持任何此类方法?谢谢 我的意思是。如果像你说的NetworkLocationService 有问题。其他基于地图的应用程序的行为方式必须相同 谷歌地图有自己的内置 NLS。这是我检查的第一件事之一 如何明确关闭NetworkLocator?因为我有解决上述问题的方法。现在我想测试一下。但无法重现此案。 您可以通过终止正在运行的服务来重现此情况(我使用 linux cmd 来终止进程)。要禁用网络提供商,您可以转到“设置”中的“定位服务”。【参考方案2】:

使用直接访问谷歌地图的解决方法:

    public static LatLng getLocationFromString(String address)
        throws JSONException 

    HttpGet httpGet = new HttpGet(
            "http://maps.google.com/maps/api/geocode/json?address="
                    + URLEncoder.encode(address, "UTF-8") + "&ka&sensor=false");
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try 
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) 
            stringBuilder.append((char) b);
        
     catch (ClientProtocolException e) 
     catch (IOException e) 
    

    JSONObject jsonObject = new JSONObject(stringBuilder.toString());

    double lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
            .getJSONObject("geometry").getJSONObject("location")
            .getDouble("lng");

    double lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
            .getJSONObject("geometry").getJSONObject("location")
            .getDouble("lat");

    return new LatLng(lat, lng);


    public static List<Address> getStringFromLocation(double lat, double lng)
        throws ClientProtocolException, IOException, JSONException 

    String address = String
            .format(Locale.ENGLISH,                                 "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language="
                            + Locale.getDefault().getCountry(), lat, lng);
    HttpGet httpGet = new HttpGet(address);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    List<Address> retList = null;

    response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
    InputStream stream = entity.getContent();
    int b;
    while ((b = stream.read()) != -1) 
        stringBuilder.append((char) b);
    

    JSONObject jsonObject = new JSONObject(stringBuilder.toString());

    retList = new ArrayList<Address>();

    if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) 
        JSONArray results = jsonObject.getJSONArray("results");
        for (int i = 0; i < results.length(); i++) 
            JSONObject result = results.getJSONObject(i);
            String indiStr = result.getString("formatted_address");
            Address addr = new Address(Locale.getDefault());
            addr.setAddressLine(0, indiStr);
            retList.add(addr);
        
    

    return retList;

【讨论】:

谢谢,它解决了我的 s3 mini 拒绝使用地理编码器服务的问题。但它仅在用于异步任务时才有效。【参考方案3】:

重启设备即可解决问题。

【讨论】:

确认!当然,如果在设备上提供后端服务 - Geocoder.isPresent()【参考方案4】:

如果设备上此类服务不可用,API 将抛出“服务不可用异常”。使用isPresent()方法检查服务是否存在。

另请参阅:http://developer.android.com/reference/android/location/Geocoder.html

【讨论】:

isPresent() 总是返回True。然而它说Service not available 我遇到了@Archie.bpgc 的同样问题【参考方案5】:

如果原始 Geocoder 失败,最好的解决方法是使用类似 Google Geocoder 的类

List<Address> addresses = null;    
Geocoder geocoder = new Geocoder(this);
addresses = geocoder.getFromLocation(...);
if (addresses == null || addresses.isEmpty())
addresses = MyGeocoder.getFromLocation(...);


import android.location.Address;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.AllClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MyGeocoder 

    public static List<Address> getFromLocation(double lat, double lng, int maxResult) 

        String address = String.format(Locale.ENGLISH, "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=false&language=" + Locale.getDefault().getCountry(), lat, lng);
        HttpGet httpGet = new HttpGet(address);
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(AllClientPNames.USER_AGENT, "Mozilla/5.0 (Java) Gecko/20081007 java-geocoder");
        client.getParams().setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 5 * 1000);
        client.getParams().setIntParameter(AllClientPNames.SO_TIMEOUT, 25 * 1000);
        HttpResponse response;

        List<Address> retList = null;

        try 
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String json = EntityUtils.toString(entity, "UTF-8");

            JSONObject jsonObject = new JSONObject(json);

            retList = new ArrayList<Address>();

            if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) 
                JSONArray results = jsonObject.getJSONArray("results");
                if (results.length() > 0) 
                    for (int i = 0; i < results.length() && i < maxResult; i++) 
                        JSONObject result = results.getJSONObject(i);
                        //Log.e(MyGeocoder.class.getName(), result.toString());
                        Address addr = new Address(Locale.getDefault());
                        // addr.setAddressLine(0, result.getString("formatted_address"));

                        JSONArray components = result.getJSONArray("address_components");
                        String streetNumber = "";
                        String route = "";
                        for (int a = 0; a < components.length(); a++) 
                            JSONObject component = components.getJSONObject(a);
                            JSONArray types = component.getJSONArray("types");
                            for (int j = 0; j < types.length(); j++) 
                                String type = types.getString(j);
                                if (type.equals("locality")) 
                                    addr.setLocality(component.getString("long_name"));
                                 else if (type.equals("street_number")) 
                                    streetNumber = component.getString("long_name");
                                 else if (type.equals("route")) 
                                    route = component.getString("long_name");
                                
                            
                        
                        addr.setAddressLine(0, route + " " + streetNumber);

                        addr.setLatitude(result.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
                        addr.setLongitude(result.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
                        retList.add(addr);
                    
                
            


         catch (ClientProtocolException e) 
            Log.e(MyGeocoder.class.getName(), "Error calling Google geocode webservice.", e);
         catch (IOException e) 
            Log.e(MyGeocoder.class.getName(), "Error calling Google geocode webservice.", e);
         catch (JSONException e) 
            Log.e(MyGeocoder.class.getName(), "Error parsing Google geocode webservice response.", e);
        

        return retList;
    

【讨论】:

【参考方案6】:

使用这个技巧。

只需编辑 project.properties

# Project target
target=Google Inc.:Google APIs:16

原因是 Geocoder 类存在于核心 Android 框架中,但依赖于 Google API 贡献的代码才能正常运行。即使您的 AVD 包含 Google API,您的项目仍需要针对该特定构建目标进行构建。

【讨论】:

【参考方案7】:

Service not Available - Geocoder Android 当我在一些煮熟的 rom 中遇到此错误时,我编写了这个库,希望对我有用。 https://github.com/dnocode/gapis

【讨论】:

【参考方案8】:

我使用的是up(直接访问Google Maps)与Geocoder代码“合并”的代码,如下所示(特别注意“try catch”):

...
//address is String
if (address != null) 
    new GeocoderTask().execute(address);

...

// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> 

    private LatLng latLng;
    private MarkerOptions markerOptions;

    @Override
    protected List<Address> doInBackground(String... locationName) 
        // Creating an instance of Geocoder class
        Geocoder geocoder = new Geocoder(getBaseContext());
        List<Address> addresses = null;

        try 
            // Getting a maximum of 3 Address that matches the input text
            addresses = geocoder.getFromLocationName(locationName[0], 3);
         catch (IOException e) 
            e.printStackTrace();
            try 
                addresses = getLocationFromString(locationName[0]);
             catch (UnsupportedEncodingException e1) 
                e1.printStackTrace();
             catch (JSONException e1) 
                e1.printStackTrace();
            

        
        return addresses;
    

    @Override
    protected void onPostExecute(List<Address> addresses) 

        if (addresses == null || addresses.size() == 0) 
            Toast.makeText(getBaseContext(), "No Location found",
                    Toast.LENGTH_SHORT).show();
            return;
        

        // Clears all the existing markers on the map
        googleMap.clear();

        // Adding Markers on Google Map for each matching address
        for (int i = 0; i < addresses.size(); i++) 

            Address address = (Address) addresses.get(i);

            // Creating an instance of GeoPoint, to display in Google Map
            latLng = new LatLng(address.getLatitude(),
                    address.getLongitude());

            String addressText = String.format(
                    "%s, %s",
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "", address
                            .getCountryName());

            markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title(addressText);

            googleMap.addMarker(markerOptions);

            // Locate the first location
            if (i == 0) 
                CameraUpdate center = CameraUpdateFactory.newLatLng(latLng);
                CameraUpdate zoom = CameraUpdateFactory.zoomTo(13);

                googleMap.moveCamera(center);
                googleMap.animateCamera(zoom);
            

        

    


public static LatLng getLocationFromString(String address)
    throws JSONException 

    HttpGet httpGet = new HttpGet(
        "http://maps.google.com/maps/api/geocode/json?address="
                + URLEncoder.encode(address, "UTF-8") + "&ka&sensor=false");
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try 
    response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
    InputStream stream = entity.getContent();
    int b;
    while ((b = stream.read()) != -1) 
        stringBuilder.append((char) b);
    
     catch (ClientProtocolException e) 
     catch (IOException e) 
    

    JSONObject jsonObject = new JSONObject(stringBuilder.toString());

    double lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
        .getJSONObject("geometry").getJSONObject("location")
        .getDouble("lng");

    double lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
        .getJSONObject("geometry").getJSONObject("location")
        .getDouble("lat");

    return new LatLng(lat, lng);


    public static List<Address> getStringFromLocation(double lat, double lng)
    throws ClientProtocolException, IOException, JSONException 

    String address = String
        .format(Locale.ENGLISH,                                 "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language="
                        + Locale.getDefault().getCountry(), lat, lng);
    HttpGet httpGet = new HttpGet(address);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    List<Address> retList = null;

    response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
    InputStream stream = entity.getContent();
    int b;
    while ((b = stream.read()) != -1) 
    stringBuilder.append((char) b);
    

    JSONObject jsonObject = new JSONObject(stringBuilder.toString());

    retList = new ArrayList<Address>();

    if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) 
    JSONArray results = jsonObject.getJSONArray("results");
    for (int i = 0; i < results.length(); i++) 
        JSONObject result = results.getJSONObject(i);
        String indiStr = result.getString("formatted_address");
        Address addr = new Address(Locale.getDefault());
        addr.setAddressLine(0, indiStr);
        retList.add(addr);
    
    

    return retList;

这对我来说非常有用,因为当地理编码器不工作时,我使用直接访问谷歌地图。

干杯!

【讨论】:

【参考方案9】:

您可以在手机中打开地图应用程序并清除缓存,然后会发现地址正常。

【讨论】:

【参考方案10】:

我遇到了相同的地理编码器错误,但未应用上述错误。它不会运行我的一台 Android 设备。然后我记得我已经意外地杀死了一些正在运行的服务。 解决方案是取出电池几秒钟,然后重新安装。 它在不更改代码的情况下工作:))

【讨论】:

实际上重启你的设备就可以了。但是您不能期望/要求您的应用用户这样做。【参考方案11】:

有些设备不支持地理编码器,所以您需要做的是创建自己的地理编码器。

基本上你需要创建一个异步任务来向 google 请求地址并处理 json 响应。

使用查询,我做这样的事情:

public void asyncJson(String address)
        address = address.replace(" ", "+");

        String url = "http://maps.googleapis.com/maps/api/geocode/json?address="+ address +"&sensor=true";

        aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() 

                @Override
                public void callback(String url, JSONObject json, AjaxStatus status)                         

                        if(json != null)

                                 //here you work with the response json
                                 JSONArray results = json.getJSONArray("results");                               
                                Toast.makeText(context, results.getJSONObject(1).getString("formatted_address"));

                        else                                
                                //ajax error, show error code
                                Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
                        
                
        );        

【讨论】:

【参考方案12】:

下面一行

Geocoder gCoder = new Geocoder(context, Locale.getDefault());

使用您的活动的Context,不要使用getApplicationContext()

【讨论】:

【参考方案13】:

我也遇到过这个错误。它发生在我最近将设备更新为 Marshmallow 时。

如果我重新启动,它会工作一次,但随后会失败,之后就根本无法工作。

我像其他人一样创建了一个 AsyncTask,它只返回 json 响应的第一个结果中的地址。

要使用下面的代码,请使用您的 api 键调用它,然后使用 Location 对象作为输入来执行 AsyncTask。您可以使用以下内容导入位置。 import android.location.Location; 您必须通过 LocationManager 请求更新来获取当前位置。

    new ReverseGeoCodeTask(GOOGLE_API_KEY).execute(location);

确保您将 api 密钥替换为您自己的密钥,并确保您在谷歌云控制台中启用它。这是您为特定项目管理所有 google api 的地方。

将此类复制为您需要反向地理编码地址的 Activity 中的内部类。

/**
 * Reverse geocode request - takes a Location in as parameters,
 * and does a network request in the background to get the first address in
 * json response. The address is returned in the onPostExecute so you
 * can update the UI with it
 */

private class ReverseGeoCodeTask extends AsyncTask<Location, Void, String>

    private final static String GEOCODE_API_ENDPOINT_BASE = "https://maps.googleapis.com/maps/api/geocode/json?latlng=";
    private final static String JSON_PROPERTY_RESULTS = "results";
    private final static String JSON_PROPERTY_FORMATTED_ADDRESS = "formatted_address";
    private final static String JSON_PROPERTY_REQUEST_STATUS = "status";
    private final static String STATUS_OK = "OK";
    private String apiKey;

    public ReverseGeoCodeTask(final String apiKey)
        this.apiKey = apiKey;
    

    @Override
    protected String doInBackground(Location... params) 

        if(apiKey == null)
            throw new IllegalStateException("Pass in a geocode api key in the ReverseGeoCoder constructor");
        

        Location location = params[0];
        String googleGeocodeEndpoint = GEOCODE_API_ENDPOINT_BASE + location.getLatitude() + "," + location.getLongitude() + "&key=" + apiKey;
        Log.d(TAG, "Requesting gecoding endpoint : " + googleGeocodeEndpoint);
            try 
                URL url = new URL(googleGeocodeEndpoint);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) 
                    result.append(line);
                

                JSONObject json = new JSONObject(result.toString());
                String requestStatus = json.getString(JSON_PROPERTY_REQUEST_STATUS);
                if(requestStatus.equals(STATUS_OK))
                    JSONArray results = json.getJSONArray(JSON_PROPERTY_RESULTS);
                    if(results.length() > 0)
                        JSONObject result1 = results.getJSONObject(0);
                        String address =  result1.getString(JSON_PROPERTY_FORMATTED_ADDRESS);
                        Log.d(TAG, "First result's address : " + address );
                        return  address;


                    
                    else
                        Log.d(TAG, "There were no results.");
                    
                
                else
                    Log.w(TAG, "Geocode request status not " + STATUS_OK + ", it was " + requestStatus );
                    Log.w(TAG, "Did you enable the geocode in the google cloud api console? Is it the right api key?");
                


            catch ( IOException | JSONException e)

                e.printStackTrace();
            

        return null;
    

    @Override
    protected void onPostExecute(String address) 
        super.onPostExecute(address);
        if(address != null)
            // update the UI here with the address, if its not null
            originEditText.setText(address);
        
        else
            Log.d(TAG, "Did not find an address, UI not being updated");
        

    

【讨论】:

API_KEY 真的是强制性的吗?没有它,我可以让它工作....不确定什么是无钥匙限制?【参考方案14】:

Android 6 上遇到了同样的问题。 问题出在应用权限。 即使地图工作正常,您也必须在应用权限中允许“获取位置”权限

最好的情况是始终检查此权限是否允许 当您期望在结果中获得该位置时。

我使用这种方法从地方获取完整地址:

public Address getFullAddress(Place place)
    Address address;

    Locale aLocale = new Locale.Builder().setLanguage("en").build();
    Geocoder geocoder = new Geocoder(this, aLocale);

    try 
        List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude,place.getLatLng().longitude, 1);

        address = addresses.get(0);

        return address;

     catch (IOException e) 
        e.printStackTrace();
    

    return null;

【讨论】:

【参考方案15】:

我有同样的错误,添加以下权限来解决它。

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

【讨论】:

没有为我解决问题,可能是因为我的设备 (Xperia S) 上根本无法使用 GeoCoder 或因为其他一些故障。【参考方案16】:
new Volly_Services(map, "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + mBinding.loc.getText().toString().trim() + "&key=Ap", getActivity()).vollyPostService().continueWithTask(task - > 
    mBinding.progressBaar.setVisibility(View.GONE);

    if (task.getResult() != null) 

        Log.e("<<<", "" + task.getResult());

        JSONObject jsonObject = new JSONObject("" + task.getResult());
        if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) 
            JSONArray results = jsonObject.getJSONArray("results");
            if (results.length() > 0) 
                mBinding.loc.setVisibility(View.GONE);
                for (int i = 0; i < results.length(); i++) 
                    JSONObject result = results.getJSONObject(i);
                    String indiStr = result.getString("formatted_address");
                    Address addr = new Address(Locale.getDefault());

                    addr.setAddressLine(0, indiStr);
                    addr.setLocality(result.getString("name"));
                    JSONObject geometry = result.getJSONObject("geometry").getJSONObject("location");
                    addr.setLatitude(geometry.getDouble("lat"));
                    addr.setLongitude(geometry.getDouble("lng"));


                    addresses.add(addr);
                
                adapter = new SerchLocationAdapter(getActivity(), addresses);
                mBinding.serchreg.setAdapter(adapter);
             else 
                Toast.makeText(getActivity(), "No result found", Toast.LENGTH_LONG).show();
            

         else 
            Toast.makeText(getActivity(), "No result found", Toast.LENGTH_LONG).show();
        
     else 
        Log.e("<<<<<<", "" + task.getError().getMessage());
        Toast.makeText(getActivity(), task.getError().getMessage(), Toast.LENGTH_LONG).show();
    
    return null;
);

【讨论】:

【参考方案17】:

我使用 Volley 并且效果很好

   private void callAppFromUrl(final String strAddress, final String app, final boolean isGeo) 
    try 
        Volley.newRequestQueue(this).add(new StringRequest(0, String.format("https://www.google.com/maps?q=%s", URLEncoder.encode(strAddress, "UTF-8")), new Response.Listener<String>() 
            public void onResponse(String response) 
                try 
                    try 
                        Matcher m = Pattern.compile("null,null,(\\d+.\\d+),(\\d+.\\d+)").matcher(response);
                        String strLatLong = "";
                        if (m.find()) 
                            strLatLong = m.group(0).replace("null,null,", "");
                        
                        String[] latlong = strLatLong.split(",");
                        LatLng latLng = new LatLng(Double.parseDouble(latlong[0]), Double.parseDouble(latlong[1]));
                        Log.d("OsK",String.valueOf(latLng));
                     catch (Exception e) 
                        Toast.makeText(getApplicationContext(), "Không tìm thấy địa chỉ", Toast.LENGTH_LONG).show();
                    
                 catch (Exception e2) 
                    Toast.makeText(getApplicationContext(), "Không tìm thấy địa chỉ", Toast.LENGTH_LONG).show();
                
            
        , new Response.ErrorListener() 
            /* class com.cantho.roadtech.MainActivity.AnonymousClass5 */

            @Override // com.android.volley.Response.ErrorListener
            public void onErrorResponse(VolleyError error) 

            
        ) 
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError 
                Map<String, String> params = new HashMap<>();
                params.put("User-Agent", "Mozilla");
                params.put("Accept-Language", "en-US,en;q=0.8");
                params.put("Referer", "google.com");
                return params;
            
        );
     catch (Exception ex) 
    

【讨论】:

以上是关于调用 geoCoder.getFromLocation() 时服务不可用的主要内容,如果未能解决你的问题,请参考以下文章

java三种调用方式(同步调用/回调/异步调用)

LINUX系统调用

引用调用 vs 复制调用调用

RPC 调用和 HTTP 调用的区别

js方法调用

深入理解Java虚拟机——方法调用(解析调用)