在實際開發中,我們會經常要獲取用戶所在的城市位置,一般來說,遇到這種需求大家第一時間都會想到集成第三方地圖來實現,比如百度或者高德。
但最近我在做一款個人項目時,卻突然想到,如果我只是需要用戶一個大概的位置,并不想獲取太多的信息,
為了這樣一個需求而去集成一個第三方是不是太浪費了?
于是就有了下面這些代碼。
不用集成第三方sdk,只是單純的獲取用戶所在的地理城市位置。
下面介紹主要步驟:
1:首先需要下面三個權限:
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.access_COARSE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />分別是網絡權限和兩個獲取地理位置的權限,不懂的同學們可以自行Google
2初始化時判斷是否有權限,因為Android6.0對于獲取用戶的位置信息有了更多的要求,需要我們動態獲取權限
另外定義三個變量
PRivate String provider;//位置提供器private LocationManager locationManager;//位置服務private Location location;//判斷是否有權限if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //權限還沒有授予,需要在這里寫申請權限的代碼 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);} else { //獲取位置的方法 dingWei();}3判斷是否動態獲取權限
//判斷是否動態獲取權限@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 1) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { dingWei(); } else { } }}4獲取位置的三個方法 然后解析網絡請求框架獲取到的json即可private void dingWei() { //權限已經被授予,在這里直接寫要執行的相應方法即可 //更改頭像 //調用相冊 locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);//獲得位置服務 provider = judgeProvider(locationManager); if (provider != null) {//有位置提供器的情況 //為了壓制getLastKnownLocation方法的警告 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } location = locationManager.getLastKnownLocation(provider); if (location != null) { getLocation(location);//得到當前經緯度并開啟線程去反向地理編碼 } else { //暫時無法獲得當前位置 } } else { //不存在位置提供器的情況 } } /** * 得到當前經緯度并開啟線程去反向地理編碼 */ public void getLocation(Location location) { String latitude = location.getLatitude() + ""; String longitude = location.getLongitude() + ""; Log.d("print", "getLocation: ---->" + latitude + " " + longitude); String url = "http://maps.google.cn/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&sensor=true,language=zh-CN";// 這里是網絡請求(我使用的是自己封裝的請求框架,你可換成你自己的網絡請求框架,請求上面這個url即可) Log.d("print", "地址是:" + url); new DownUtil().setOnDownListener(this).downJSON(url); } /** * 判斷是否有可用的內容提供器 * * @return 不存在返回null */ private String judgeProvider(LocationManager locationManager) { List<String> prodiverlist = locationManager.getProviders(true); if (prodiverlist.contains(LocationManager.NETWORK_PROVIDER)) { return LocationManager.NETWORK_PROVIDER; } else if (prodiverlist.contains(LocationManager.GPS_PROVIDER)) { return LocationManager.GPS_PROVIDER; } else { Toast.makeText(MainActivity.this, "沒有可用的位置提供器,請手動打開定位權限", Toast.LENGTH_SHORT).show(); } return null; }
新聞熱點
疑難解答