码迷,mamicode.com
首页 > 移动开发 > 详细

Android 定位模板

时间:2018-01-25 15:52:34      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:manage   col   ddr   gets   nal   prot   city   contex   fine   

private void getLocationCity(){

        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(serviceName);
//        String provider = LocationManager.GPS_PROVIDER;
        String provider = LocationManager.NETWORK_PROVIDER;

        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);
     locationManager.requestLocationUpdates(provider, 2000, 10,
                locationListener);
        Location location = locationManager.getLastKnownLocation(provider);
        getAddress(location);   
    }

    private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            getAddress(location);
        }
        public void onProviderDisabled(String provider){
            getAddress(null);
        }
        public void onProviderEnabled(String provider){ }
        public void onStatusChanged(String provider, int status,
                                    Bundle extras){ }
    };

    private void getAddress(Location location) {

        if (location != null) {
            new MyAsyncCity().execute(location);
        } else {
            Log.d(TAG, "updateWithNewLocation: ");
        }
    }

    private class MyAsyncCity extends AsyncTask<Location, Void, String> {

        @Override
        protected String doInBackground(Location... params) {
            List<Address> addList = null;
            Geocoder ge = new Geocoder(WelcomeActivity.this);
            try {
                addList = ge.getFromLocation(params[0].getLatitude(), params[0].getLongitude(), 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return addList.get(0).getLocality();
        }

        @Override
        protected void onPostExecute(String city) {
            super.onPostExecute(city);
            spUtil.setLocationCity(city);
        }
    }

 

Android 定位模板

标签:manage   col   ddr   gets   nal   prot   city   contex   fine   

原文地址:https://www.cnblogs.com/IT-lss/p/8350981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!