Android 如何使用GPS&;获取当前位置的完整详细信息;位置管理器

Android 如何使用GPS&;获取当前位置的完整详细信息;位置管理器,android,android-emulator,android-location,Android,Android Emulator,Android Location,我正在使用GPS获取一个位置的经纬度,但现在我想获取该位置的每个细节,如:国家、城市、州、邮政编码、街道号码等。 当前位置的最大详细信息 代码: private void initmaintent(){ LocationResult LocationResult=新的LocationResult(){ @凌驾 公共位置(位置){ 如果(位置!=null){ Geocoder gcd=新的Geocoder(getApplicationContext(), Locale.getDefault());

我正在使用GPS获取一个位置的经纬度,但现在我想获取该位置的每个细节,如:国家、城市、州、邮政编码、街道号码等。 当前位置的最大详细信息

代码:

private void initmaintent(){
LocationResult LocationResult=新的LocationResult(){
@凌驾
公共位置(位置){
如果(位置!=null){
Geocoder gcd=新的Geocoder(getApplicationContext(),
Locale.getDefault());
列出地址;
试一试{
addresses=gcd.getFromLocation(location.getLatitude(),
location.getLongitude(),1);
如果(地址.size()>0){
String s=“地址行:”
+地址。get(0)。getAddressLine(0)+“\n”
+地址。get(0)。getFeatureName()+“\n”
+“地点:”
+地址。get(0)。GetLocation()+“\n”
+地址。get(0)。getPremises()+“\n”
+“管理区域:”
+地址。get(0)。getAdminArea()+“\n”
+“国家代码:”
+地址。get(0)。getCountryCode()+“\n”
+“国家名称:”
+地址。get(0)。getCountryName()+“\n”
+电话:+地址。获取(0)。获取电话()
+“\n”+“邮箱:”
+地址。get(0)。getPostalCode()+“\n”
+“次局部性:”
+地址。get(0)。getSubLocality()+“\n”
+“SubAdminArea:”
+地址。get(0)。getSubAdminArea()+“\n”
+“地下通道:”
+addresses.get(0.getSubthorougheare())
+“\n”+“通道:”
+地址。get(0)。GetThroughure()+“\n”
+URL:+地址.get(0.getUrl();
locationNotFound.setVisibility(View.GONE);
locationFound.setVisibility(View.VISIBLE);
foundLocationText.setText;
}
}捕获(IOE异常){
e、 printStackTrace();
}
背景(location.getLatitude(),location.getLatitude());
}
}
};
MyLocation MyLocation=新的MyLocation();
myLocation.getLocation(这是locationResult);
}
公共类位置{
定时器1;
位置经理lm;
定位结果定位结果;
布尔值gps_enabled=false;
布尔网络_enabled=false;
公共布尔getLocation(上下文、LocationResult){
//我使用LocationResult回调类从
//MyLocation到用户代码。
位置结果=结果;
如果(lm==null)
lm=(LocationManager)上下文
.getSystemService(Context.LOCATION\u服务);
//如果不允许提供程序,将引发异常。
试一试{
gps_enabled=lm.isProviderEnabled(LocationManager.gps_PROVIDER);
}捕获(例外情况除外){
}
试一试{
网络已启用=lm
.isProviderEnabled(LocationManager.NETWORK_提供商);
}捕获(例外情况除外){
}
//如果未启用任何提供程序,则不要启动侦听器
如果(!gps_已启用&&!网络_已启用)
返回false;
如果(gps_已启用)
lm.RequestLocationUpdate(LocationManager.GPS_提供程序,0,0,
位置(GPS);
如果(网络已启用)
lm.RequestLocationUpdate(LocationManager.NETWORK_提供程序,0,0,
位置监听器网络);
timer1=新定时器();
timer1.schedule(新GetLastLocation(),20000);
返回true;
}
LocationListener locationListenerGps=新LocationListener(){
已更改位置上的公共无效(位置){
timer1.cancel();
locationResult.gotLocation(位置);
lm.移除更新(本);
lm.RemoveUpdate(locationListenerNetwork);
}
公共无效onProviderDisabled(字符串提供程序){
}
公共无效onProviderEnabled(字符串提供程序){
}
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
}
};
LocationListener locationListenerNetwork=新LocationListener(){
已更改位置上的公共无效(位置){
timer1.cancel();
如果(位置!=null){
System.out.println(location.getLatitude());
}
locationResult.gotLocation(位置);
lm.移除更新(本);
lm.移除更新(locationListenerGps);
}
公共无效onProviderDisabled(字符串提供程序){
}
公共无效onProviderEnabled(字符串提供程序){
}
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
}
};
类GetLastLocation扩展了TimerTask{
@凌驾
公开募捐{
lm.移除更新(locationListenerGps);
lm.RemoveUpdate(locationListenerNetwork);
位置网位置=零,gps位置=零;
如果(gps_已启用)
gps_loc=lm.getLastKnownLocation(LocationManager.gps_PROVIDER);
如果(网络已启用)
净位置=lm
  public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
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
String country;

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

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

// Declaring a Location Manager
protected LocationManager locationManager;

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

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;
            if (isNetworkEnabled) {
                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) {
                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();
                longitude = location.getLongitude();

                        }
                    }
                }
            }
        }

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

    return location;
 }
private void initmainIntent() {

    LocationResult locationResult = new LocationResult() {

        @Override
        public void gotLocation(Location location) {
            if (location != null) {
                Geocoder gcd = new Geocoder(getApplicationContext(),
                        Locale.getDefault());
                List<Address> addresses;
                try {
                    addresses = gcd.getFromLocation(location.getLatitude(),
                            location.getLongitude(), 1);

                    if (addresses.size() > 0) {
                        String s = "Address Line: "
                                + addresses.get(0).getAddressLine(0) + "\n"
                                + addresses.get(0).getFeatureName() + "\n"
                                + "Locality: "
                                + addresses.get(0).getLocality() + "\n"
                                + addresses.get(0).getPremises() + "\n"
                                + "Admin Area: "
                                + addresses.get(0).getAdminArea() + "\n"
                                + "Country code: "
                                + addresses.get(0).getCountryCode() + "\n"
                                + "Country name: "
                                + addresses.get(0).getCountryName() + "\n"
                                + "Phone: " + addresses.get(0).getPhone()
                                + "\n" + "Postbox: "
                                + addresses.get(0).getPostalCode() + "\n"
                                + "SubLocality: "
                                + addresses.get(0).getSubLocality() + "\n"
                                + "SubAdminArea: "
                                + addresses.get(0).getSubAdminArea() + "\n"
                                + "SubThoroughfare: "
                                + addresses.get(0).getSubThoroughfare()
                                + "\n" + "Thoroughfare: "
                                + addresses.get(0).getThoroughfare() + "\n"
                                + "URL: " + addresses.get(0).getUrl();
                        locationNotFound.setVisibility(View.GONE);
                        locationFound.setVisibility(View.VISIBLE);
                        foundLocationText.setText(s);
                    }

                } catch (IOException e) {

                    e.printStackTrace();
                }

                background(location.getLatitude(), location.getLongitude());
            }
        }
    };
    MyLocation myLocation = new MyLocation();
    myLocation.getLocation(this, locationResult);
}



public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled = false;
    boolean network_enabled = false;

    public boolean getLocation(Context context, LocationResult result) {
        // I use LocationResult callback class to pass location value from
        // MyLocation to user code.
        locationResult = result;
        if (lm == null)
            lm = (LocationManager) context
                    .getSystemService(Context.LOCATION_SERVICE);

        // exceptions will be thrown if provider is not permitted.
        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }
        try {
            network_enabled = lm
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        // don't start listeners if no provider is enabled
        if (!gps_enabled && !network_enabled)
            return false;

        if (gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                    locationListenerGps);
        if (network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                    locationListenerNetwork);
        timer1 = new Timer();
        timer1.schedule(new GetLastLocation(), 20000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

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

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            if (location != null) {
                System.out.println(location.getLatitude());

            }
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

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

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
            lm.removeUpdates(locationListenerGps);
            lm.removeUpdates(locationListenerNetwork);

            Location net_loc = null, gps_loc = null;
            if (gps_enabled)
                gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (network_enabled)
                net_loc = lm
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            // if there are both values use the latest one
            if (gps_loc != null && net_loc != null) {
                if (gps_loc.getTime() > net_loc.getTime())
                    locationResult.gotLocation(gps_loc);
                else
                    locationResult.gotLocation(net_loc);
                return;
            }

            if (gps_loc != null) {
                locationResult.gotLocation(gps_loc);
                return;
            }
            if (net_loc != null) {
                locationResult.gotLocation(net_loc);
                return;
            }
            locationResult.gotLocation(null);
        }
    }

    public static abstract class LocationResult {
        public abstract void gotLocation(Location location);
    }
}
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
        List<Address> addresses = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        String address = "";
        if (addresses != null && addresses.size() >= 0) {
            address = addresses.get(0).getAddressLine(0);

            if (addresses != null && addresses.size() >= 1) {
                address += ", " + addresses.get(0).getAddressLine(1);
            }

            if (addresses != null && addresses.size() >= 2) {
                address += ", " + addresses.get(0).getAddressLine(2);
            }
        }
    private class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {

        editLocation.setText("");
        pb.setVisibility(View.INVISIBLE);
        Toast.makeText(
                getBaseContext(),
                "Location changed : Lat: " + loc.getLatitude() + " Lng: "
                        + loc.getLongitude(), Toast.LENGTH_SHORT).show();
        String longitude = "Longitude: " + loc.getLongitude();
        Log.v(TAG, longitude);
        String latitude = "Latitude: " + loc.getLatitude();
        Log.v(TAG, latitude);

        /*----------to get City-Name from coordinates ------------- */
        String cityName = null;
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(loc.getLatitude(),
                    loc.getLongitude(), 1);
            if (addresses.size() > 0)
                System.out.println(addresses.get(0).getLocality());
            cityName = addresses.get(0).getLocality();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String s = longitude + "\n" + latitude + "\n\nMy Currrent City is: "
                + cityName;
        editLocation.setText(s);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
} 
public class StoreFinder extends FragmentActivity implements
    OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

    private GoogleMap mMap;
    private GoogleApiClient googleApiClient;
    private LocationRequest locationRequest;
    private Location lastLocation;
    private Marker currentUserLocationMarker;
    private static final int Request_User_Location_Code = 99;
    private double latitude;
    double longitude;
    private int ProximityRadius = 10000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_location);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            checkUserLocationPermission();
        }


        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        {
            buildGoogleApiClient();

            mMap.setMyLocationEnabled(true);
        }

    }

    public boolean checkUserLocationPermission()
    {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
            {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
            }
            else
            {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
            }
            return false;
        }
        else
        {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        switch (requestCode)
        {
            case Request_User_Location_Code:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                    {
                        if (googleApiClient == null)
                        {
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }
                }
                else
                {
                    Toast.makeText(this, "Permission Denied...", Toast.LENGTH_SHORT).show();
                }
                return;
        }
    }

    protected synchronized void buildGoogleApiClient()
    {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        googleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location)
    {
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        lastLocation = location;

        if (currentUserLocationMarker != null)
        {
            currentUserLocationMarker.remove();
        }

          /*----------to get City-Name from coordinates ------------- */
        String cityName = null;
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(latitude, latitude, 1);
            if (addresses.size() > 0)
                System.out.println(addresses.get(0).getLocality());
                cityName = addresses.get(0).getAddressLine(0);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String s =  cityName;

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title(s);
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

        currentUserLocationMarker = mMap.addMarker(markerOptions);

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomBy(16));

        if (googleApiClient != null)
        {
            LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle)
    {
        locationRequest = new LocationRequest();
        locationRequest.setInterval(1100);
        locationRequest.setFastestInterval(1100);
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        {
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, (LocationListener) this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}