安卓LocationManager获取当前地理位置(经纬度)

1.首先创建LocationManager对象

2调用方法得到位置信息

3.设置监听,监听位置变化信息

代码:

public class MainActivity extends AppCompatActivity {

    private TextView tv_jing;//经度
    private TextView tv_wei;//维度

    public final LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            updateToNewLocation(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            updateToNewLocation(null);
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //创建位置管理器对象
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //检测权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        //提供者
        String provider;
        //获取可以定位的所有提供者
        List providerList = locationManager.getProviders(true);
        if (providerList.contains(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
            locationManager.requestLocationUpdates(provider, Integer.MAX_VALUE, 0, mLocationListener);
        }
        if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
            locationManager.requestLocationUpdates(provider, Integer.MAX_VALUE, 0, mLocationListener);
        }
        if (providerList.contains(LocationManager.PASSIVE_PROVIDER)) {
            provider = LocationManager.PASSIVE_PROVIDER;
            locationManager.requestLocationUpdates(provider, Integer.MAX_VALUE, 0, mLocationListener);
        }
    }

    private void initView() {
        tv_jing = (TextView) findViewById(R.id.tv_jing);
        tv_wei = (TextView) findViewById(R.id.tv_wei);
    }

    private void updateToNewLocation(Location location) {
        double lat;//维度
        double lng;//经度

        if (location != null) {
            lat = location.getLatitude();
            lng = location.getLongitude();
            tv_jing.setText("经度:" + lng);
            tv_wei.setText("维度:" + lat);
        }
    }
}

你可能感兴趣的:(Android)