在Lollipop和Marshmallow找不到位置提供商

时间:2017-01-30 08:38:28

标签: android google-maps gps

我正在使用项目来查找使用纬度和经度的地址。我在Jellybean得到了答案但是当来到Lollipop和Marshmallow时它只显示纬度和经度,没有得到地址。它显示找不到位置提供程序。我的代码中有错误吗?

 locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    mprovider = locationManager.getBestProvider(criteria, false);

    if (mprovider != null && !mprovider.equals("")) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(mprovider);
     locationManager.requestLocationUpdates(mprovider,5000, 0,this);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        if (location != null)
            onLocationChanged(location);
        else
            Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onLocationChanged(Location location) {
    TextView longitude = (TextView) findViewById(R.id.textView);
    TextView latitude = (TextView) findViewById(R.id.textView1);

    longitude.setText("Current Longitude:" + location.getLongitude());
    latitude.setText("Current Latitude:" + location.getLatitude());
    Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault());

    // String mylocation;
    try {
        List < Address > addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        if (addresses != null && addresses.size() > 0) {
            String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
            address1.setText(address);
            String city = addresses.get(0).getLocality();
            textViewCity.setText(city);
            String state = addresses.get(0).getAdminArea();
            textViewState.setText(state);
            String country = addresses.get(0).getCountryName();
            textViewCountry.setText(country);
            String postalCode = addresses.get(0).getPostalCode();
            textViewPostal.setText(postalCode);
            String knownName = addresses.get(0).getFeatureName();

            System.out.println("Address >> " + address + " " +city+ " \n" + state + " \n" + country+ "\n"+postalCode+ "\n"+knownName);

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

1 个答案:

答案 0 :(得分:1)

添加此课程。

public class SingleShotLocationProvider {

    public static interface LocationCallback {
        public void onNewLocationAvailable(GPSCoordinates location);
    }

    // calls back to calling thread, note this is for low grain: if you want higher precision, swap the
    // contents of the else and if. Also be sure to check gps permission/settings are allowed.
    // call usually takes <10ms
    public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
        final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (isNetworkEnabled) {
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            locationManager.requestSingleUpdate(criteria, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
                }

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

                @Override
                public void onProviderEnabled(String provider) {
                }

                @Override
                public void onProviderDisabled(String provider) {
                }
            }, null);
      } else {
          boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
          if (isGPSEnabled) {
              Criteria criteria = new Criteria();
              criteria.setAccuracy(Criteria.ACCURACY_FINE);
              locationManager.requestSingleUpdate(criteria, new LocationListener() {
                  @Override
                  public void onLocationChanged(Location location) {
                      callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
                  }

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


  // consider returning Location instead of this dummy wrapper class
  public static class GPSCoordinates {
      public float longitude = -1;
      public float latitude = -1;

      public GPSCoordinates(float theLatitude, float theLongitude) {
          longitude = theLongitude;
          latitude = theLatitude;
      }

      public GPSCoordinates(double theLatitude, double theLongitude) {
          longitude = (float) theLongitude;
          latitude = (float) theLatitude;
      }
  }  
}

并使用如下:

SingleShotLocationProvider.requestSingleUpdate(getActivity(),
                            new SingleShotLocationProvider.LocationCallback() {
                                @Override
                                public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
                                    lat = location.latitude;
                                    lag = location.longitude;
                                }
                            });

如果您的设备位置已启用,则可以获得lat-lag。所以也要检查是否启用。

if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    showEnableLocationDialog();
                } else {
                                    SingleShotLocationProvider.requestSingleUpdate(getActivity(),
                            new SingleShotLocationProvider.LocationCallback() {
                                @Override
                                public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
                                    lat = location.latitude;
                                    lag = location.longitude;
                                }
                            });
                }



public void showEnableLocationDialog() {
        final android.app.AlertDialog.Builder builderDialog = new android.app.AlertDialog.Builder(getActivity());
        builderDialog.setTitle("Enable Location");
        builderDialog.setMessage("Please enable location for near by search");
        builderDialog.setPositiveButton("Enable",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(myIntent);
                    }
                });
        builderDialog.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //fetchImages();
                    }
                });
        android.app.AlertDialog alert = builderDialog.create();
        alert.show();
    }

我希望您首先要求获得位置的运行时权限。否则你永远不会得到位置。