Android 获取经纬度同时获取当前具体城市信息

本博客内容

  1. 获取经纬度,显示到界面
  2. 获取城市信息,通过吐司显示。如宁夏回族自治区银川市…

具体代码

  1. AndroidManifest.xml
    
    
  1. Main2Activity.java
package com.example.tnt.gps;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        LocationManager locationManager;
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(serviceName);
//                String provider = LocationManager.GPS_PROVIDER;  
//                String provider = "gps";  

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(criteria, true);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
        }
        Location location = locationManager.getLastKnownLocation(provider);
        updateWithNewLocation(location);
        locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);

    }
    private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            updateWithNewLocation(location);
        }

        public void onProviderDisabled(String provider) {
            updateWithNewLocation(null);
        }

        public void onProviderEnabled(String provider) {
        }

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

    private void updateWithNewLocation(Location location) {
        String latLongString;
        TextView myLocationText;
        myLocationText = findViewById(R.id.myLocationText);
//                try {
//                        Thread.sleep(0);//因为真机获取gps数据需要一定的时间,为了保证获取到,采取系统休眠的延迟方法
//                } catch (InterruptedException e) {
//                        e.printStackTrace();
//                        throw new RuntimeException(e);
//                }
        if (location != null) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();

            Geocoder geocoder=new Geocoder(this);
            List places = null;

            try {
                places = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 5);
                Toast.makeText(Main2Activity.this, places.size()+"", Toast.LENGTH_LONG).show();
                System.out.println(places.size()+"");
            } catch (Exception e) {
                e.printStackTrace();
            }

            String placename = "";
            if (places != null && places.size() > 0) {
                // placename=((Address)places.get(0)).getLocality();
                //一下的信息将会具体到某条街
                //其中getAddressLine(0)表示国家,getAddressLine(1)表示精确到某个区,getAddressLine(2)表示精确到具体的街
                placename = ((Address) places.get(0)).getAddressLine(0) + ", " + System.getProperty("line.separator")
                        + ((Address) places.get(0)).getAddressLine(1) + ", "
                        + ((Address) places.get(0)).getAddressLine(2);
            }

            latLongString = "纬度:" + lat + "/n经度:" + lng;
            Toast.makeText(Main2Activity.this, placename, Toast.LENGTH_LONG).show();
        } else {
            latLongString = "无法获取地理信息";
        }
        myLocationText.setText("您当前的位置是:/n" + latLongString);
    }
}

你可能感兴趣的:(Android)