获取自己的经纬度 LocationManager

package com.gao.locationtest;

/**
 * LocationManager
 * 确定自己位置的经纬度
 */
public class MainActivity extends AppCompatActivity {
    TextView show_location;
    LocationManager mLocationManager;

    String provider; //位置提供器

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

        show_location = (TextView) findViewById(R.id.show_location);
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);


        //置提供器
        List providerList = mLocationManager.getProviders(true);
        if (providerList.contains(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;

        } else {
            // 当没有可用的位置提供器时,弹出Toast提示用户
            Toast.makeText(this, "No location provider to use", Toast.LENGTH_SHORT).show();
            return;
        }

        Location location = mLocationManager.getLastKnownLocation(provider);
        if (location != null) {
        // 显示当前设备的位置信息
            showLocation(location);
        }

        mLocationManager.requestLocationUpdates(provider, 5000, 10, locationListener);
    }

    protected void onDestroy() {
        super.onDestroy();
        if (mLocationManager != null) {
// 关闭程序时将监听器移除
            mLocationManager.removeUpdates(locationListener);
        }
    }

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            // 更新当前设备的位置信息
            showLocation(location);
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    private void showLocation(Location location) {
        String currentPosition = "latitude is " + location.getLatitude() + "\n"
                + "longitude is " + location.getLongitude();
        show_location.setText(currentPosition);
    }
}

这里 requestLocationUpdates()方法接收四个参数,第一个参数是位置提供器的类型,第
二个参数是监听位置变化的时间间隔,以毫秒为单位,第三个参数是监听位置变化的距离间
隔,以米为单位,第四个参数则是 LocationListener监听器。这样的话,LocationManager每隔
5秒钟会检测一下位置的变化情况,当移动距离超过 10米的时候,就会调用 LocationListener
的 onLocationChanged()方法,并把新的位置信息作为参数传入

你可能感兴趣的:(Android)