android開發(fā)怎么獲得手機(jī)的gps?
第一步,申明權(quán)限。(5.0之后權(quán)限需要?jiǎng)討B(tài)申請,具體代碼和這個(gè)問題無關(guān)就不貼出來了)
<!--定位權(quán)限-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
第二步通過LocationManager類獲取位置信息,下面是一個(gè)封裝好的工具類
**
* Created by DELL zhanghuirong on 2019/3/15.
* 獲取當(dāng)前位置信息
*/
public class MyLocationUtil {
private static String provider;
public static Location getMyLocation() {
// 獲取當(dāng)前位置信息
//獲取定位服務(wù)
LocationManager locationManager = (LocationManager) MyApp.getContext().getSystemService(Context.LOCATION_SERVICE);
//獲取當(dāng)前可用的位置控制器
List<String> list = locationManager.getProviders(true);
if (list.contains(locationManager.GPS_PROVIDER)) {
// GPS位置控制器
provider = locationManager.GPS_PROVIDER;//GPS定位
} else if (list.contains(locationManager.NETWORK_PROVIDER)) {
// 網(wǎng)絡(luò)位置控制器
provider = locationManager.NETWORK_PROVIDER;//網(wǎng)絡(luò)定位
}
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: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
Location lastKnownLocation = locationManager.getLastKnownLocation(provider);
return lastKnownLocation;
} else {
ToastUtils.makeText("請檢查網(wǎng)絡(luò)或GPS是否打開");
}
return null;
}
}
第三步(其實(shí)到上一步這個(gè)問題已經(jīng)解決了,這個(gè)算擴(kuò)展吧)將位置信息轉(zhuǎn)換成地址信息。
在高德或者百度地圖開發(fā)者平臺(tái)申請?jiān)L問api許可。將第二步獲取到的經(jīng)緯度信息上傳查詢對應(yīng)坐標(biāo)信息。因?yàn)榘俣群透叩掠玫牟皇峭粋€(gè)坐標(biāo)系,查詢時(shí)仔細(xì)看官方API。