常用方法:
xml文件的配置
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
這個方法返回值是經緯度的組合字符串 組合格式Latitude + "-" + Longitude;,如有需要可以自行修改
private String getLocal() {
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
//獲取所有可用的位置提供器
List<String> providers = locationManager.getProviders(true);
if (providers.contains(LocationManager.GPS_PROVIDER)) {
//如果是GPS
locationProvider = LocationManager.GPS_PROVIDER;
} else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
//如果是Network
locationProvider = LocationManager.NETWORK_PROVIDER;
} else {
Toast.makeText(view.getContext(), "沒有可用的位置提供器", Toast.LENGTH_SHORT).show();
return "null";
}
//獲取Location
if (ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return "未獲取權限";
}
//不是一次就能成功的
locl = locationManager.getLastKnownLocation(locationProvider);
if(locl!=null){
//不爲空,顯示地理位置經緯度
locationManager.requestLocationUpdates("gps", 60000, 1, locationListener);
Latitude = locl.getLatitude();
Longitude = locl.getLongitude();
}
//監視地理位置變化
locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
locationstr = Latitude + "-" + Longitude;
return locationstr;
}
然後開始碼的時候發現每次第一次總是獲取不到地理位置,返回值都是null-null,分析後得知原因是getLastKnownLocation這個方法用一次往往不能成功,所以在判斷不爲空的時候反覆獲取,即加上下面一句話
locationManager.requestLocationUpdates("gps", 60000, 1, locationListener);
這是從國外論壇上得到的啓發
具體可見 http://stackoverflow.com/questions/1608632/android-locationmanager-getlastknownlocation-returns-null