1. 程式人生 > >安卓LocationManager獲取當前地理位置(經緯度)

安卓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<String> 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);
        }
    }
}