第壹步,申明權限。(5.0之後權限需要動態申請,具體代碼和這個問題無關就不貼出來了)
<!--定位權限-->
<uses-permissionandroid:name=\"android.permission.ACCESS_FINE_LOCATION\"/>
<uses-permissionandroid:name=\"android.permission.ACCESS_COARSE_LOCATION\"/>
第二步通過LocationManager類獲取位置信息,下面是壹個封裝好的工具類
**
*CreatedbyDELLzhanghuirongon2019/3/15.
*獲取當前位置信息
*/
publicclassMyLocationUtil{
privatestaticStringprovider;
publicstaticLocationgetMyLocation(){
//獲取當前位置信息
//獲取定位服務
LocationManagerlocationManager=(LocationManager)MyApp.getContext().getSystemService(Context.LOCATION_SERVICE);
//獲取當前可用的位置控制器
List<String>list=locationManager.getProviders(true);
if(list.contains(locationManager.GPS_PROVIDER)){
//GPS位置控制器
provider=locationManager.GPS_PROVIDER;//GPS定位
}elseif(list.contains(locationManager.NETWORK_PROVIDER)){
//網絡位置控制器
provider=locationManager.NETWORK_PROVIDER;//網絡定位
}
if(provider!=null){
if(ActivityCompat.checkSelfPermission(MyApp.getContext(),Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED&&ActivityCompat.checkSelfPermission(MyApp.getContext(),Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
//TODO:Considercalling
//ActivityCompat#requestPermissions
//heretorequestthemissingpermissions,andthenoverriding
//publicvoidonRequestPermissionsResult(intrequestCode,String[]permissions,
//int[]grantResults)
//tohandlethecasewheretheusergrantsthepermission.Seethedocumentation
//forActivityCompat#requestPermissionsformoredetails.
returnnull;
}
LocationlastKnownLocation=locationManager.getLastKnownLocation(provider);
returnlastKnownLocation;
}else{
ToastUtils.makeText(\"請檢查網絡或GPS是否打開\");
}
returnnull;
}
}
第三步(其實到上壹步這個問題已經解決了,這個算擴展吧)將位置信息轉換成地址信息。
在高德或者百度地圖開發者平臺申請訪問api許可。將第二步獲取到的經緯度信息上傳查詢對應坐標信息。因為百度和高德用的不是同壹個坐標系,查詢時仔細看官方API。
直接通過安卓的原生接口獲取壹個gps的位置意義不是很大。這個數據在壹定的坐標系上才有意義。建議去高德的開發平臺註冊個帳號,引入sdk來做,地理位置與地理位置解析的概念先了解下吧。
//第壹步先獲取LocationManager的對象LocationManagerGpsManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);//通過LocationManager的對象來獲取到Location的信息。Locationlocation=GpsManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);//Location中經常用到的有以下幾種:/*location.getAccuracy();精度location.getAltitude();高度:海拔location.getBearing();導向location.getSpeed();速度location.getLatitude();緯度location.getLongitude();經度location.getTime();UTC時間以毫秒計*/註:需要添加使用權限的哦