2

我开发的应用程序在运行时使用 GPSTracker.java 类按纬度和经度取城市名称,并将该城市名称添加到 url 以检索 json 数据。我的代码从 API 18 到 API 22 运行良好,但是现在当我在 API 23 上运行我的代码时,地理编码器不起作用并且城市名称为空 这是我在 Main Activity 上用于检索城市名称的代码:

// To get City-Name from coordinates
    GPSTracker gpsTracker = new GPSTracker(getActivity());






    String cityName = null;
    Geocoder gcd = new Geocoder(getContext(), Locale.ENGLISH);
    List<Address> addresses = null;
    try {
        addresses = gcd.getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
        if (addresses.size() > 0) {
            System.out.println(addresses.get(0).getLocality());
            cityName = addresses.get(0).getLocality();
            Log.d("nome_cit", "debug_cit " + cityName);
            // Controllo formattazione nomi Car2Go
            if(cityName.equals("Rome")) {
                nome_citta = "Roma";
            }else if (cityName.equals("Florence")){
                nome_citta = "Firenze";
            }
            else if (cityName.equals("Milan")){
                nome_citta = "Milano";
            }
            else if (cityName.equals("Turin")){
                nome_citta = "Torino";
            }else if (cityName.equals("New York")){
                nome_citta = "NewYorkCity";
            }else if (cityName.equals("Los Angeles")){
                nome_citta = "LosAngeles";
            }
            else if (cityName.equals("San Diego")){
                nome_citta = "SanDiego";
            }
            else if (cityName.equals("Twin Cities")){
                nome_citta = "TwinCities";
            }
            else if (cityName.equals("Vienna")) {
                nome_citta = "wien";

            }
            else if (cityName.equals("Munich")) {
                nome_citta = "München";
            }
            else if (cityName.equals("Osler")) {
                nome_citta = "Rheinland";
            }
            // Controllo formattazione JCDecaux
            else if (cityName.equals("Valencia")) {
                nome_citta_test = "Valence";
            }
            else if (cityName.equals("Parigi")) {
                nome_citta_test = "Paris";
            }
            else if (cityName.equals("Besançon")){
                nome_citta_test = "Besancon";
            }
            else if (cityName.equals("Créteil")) {
                nome_citta_test = "Creteil";
            }
            else {
                nome_citta = cityName;
                nome_citta_test = cityName;
            }
        }
        else {

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

    }

在我的位置的地图上,我设置了此权限:

if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager
                .PERMISSION_GRANTED && ActivityCompat
                .checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager
                .PERMISSION_GRANTED) {

            /*Toast.makeText(getActivity(),
                    "Need location permission for   map.setMyLocationEnabled(true);",
                    Toast.LENGTH_LONG).show();*/

            MultiplePermissionsListener snackbarMultiplePermissionsListener =
                    SnackbarOnAnyDeniedMultiplePermissionsListener.Builder
                            .with((ViewGroup) getView(), "La app ha bisogno di ablitare i permessi di localizzaione per mostrare la mappa")
                            .withOpenSettingsButton("Settings")
                            .withCallback(new Snackbar.Callback() {
                                @Override
                                public void onShown(Snackbar snackbar) {
                                    // Event handler for when the given Snackbar has been dismissed
                                }

                                @Override
                                public void onDismissed(Snackbar snackbar, int event) {
                                    // Event handler for when the given Snackbar is visible
                                }
                            })
                            .build();
            Dexter.checkPermissions(snackbarMultiplePermissionsListener, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE, Manifest.permission.GET_ACCOUNTS);
            return;
        }

这是我的 GPSTracker.java 类:

public final class GPSTracker implements LocationListener {

private final Context mContext;

// flag for GPS status
public boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

/**
 * Function to get the user's current location
 *
 * @return
 */
public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(Context.LOCATION_SERVICE);

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

        Log.v("isGPSEnabled", "=" + isGPSEnabled);

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

        Log.v("isNetworkEnabled", "=" + isNetworkEnabled);

        if (isGPSEnabled == false && isNetworkEnabled == false) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                location=null;
                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();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                location=null;
                if (location == null) {
                    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();
      //                                DecimalFormat latitude = new                  DecimalFormat("00.00");
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

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

    return location;
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 *
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog On pressing Settings button will
 * lauch Settings Options
 * */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle(R.string.title);

    // Setting Dialog Message
    alertDialog
            .setMessage(R.string.subtitle);

    // On pressing Settings button
    alertDialog.setPositiveButton(R.string.impostazioni,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

    // on pressing cancel button
    alertDialog.setNegativeButton(R.string.cancella,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    alertDialog.setCancelable(false);

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

}

我还注意到,在 API 23 上使用地点选择器我收到此错误:尝试在此代码的空对象引用上调用接口方法“int java.util.List.size()”:

if (resultCode == getActivity().RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(getActivity(), data);
                String addresses = place.getAddress().toString();
                if (addresses != null) {
                    puntoA.setText(addresses);
                }if (addresses.isEmpty()){
                    addresses = "(" + place.getLatLng().latitude + "," + place.getLatLng().longitude + ")";
                    puntoA.setText("nessun indirizzo disponibile " + addresses);

                }
                //puntoA.setText(addresses);
                // Recupero coordinate
                Geocoder geocoder = new Geocoder(getActivity());
                List<Address> address = null;
                try {
                    address = geocoder.getFromLocationName(addresses, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(address.size() > 0) {
                    Lat = address.get(0).getLatitude();
                    Lon = address.get(0).getLongitude();
                }
                else if (address.size() == 0) {
                    Lat = place.getLatLng().latitude;
                    Lon = place.getLatLng().longitude;
                }

而且这个功能在其他 API 版本上也能很好地工作有什么帮助吗?

4

1 回答 1

0

现在我的代码在 API 23 上运行良好,我使用以下代码:

// To get City-Name from coordinates
    GPSTracker gpsTracker = new GPSTracker(getActivity());
    Double LatFab = gpsTracker.getLatitude();
    Double LonFab = gpsTracker.getLongitude();

    List<Address> geocodeMatchess = null;
    String Country_;

    try {
        geocodeMatchess = new Geocoder(getActivity(), Locale.ENGLISH).getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
        if (geocodeMatchess.isEmpty()) {

        }else {
            Country_ = geocodeMatchess.get(0).getLocality();
            citta_fab = Country_;
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

希望这对你有帮助

于 2016-09-13T13:11:55.620 回答