我需要以编程方式使用 GPS 获取当前位置。
我怎样才能实现它?
我创建了一个小应用程序,其中包含分步说明,用于获取当前位置的 GPS 坐标。
完整的示例源代码位于获取当前位置坐标、城市名称 - 在 Android 中 http://www.rdcworld-android.blogspot.in/2012/01/get-current-location-coordinates-city.html.
看看它怎么运作:
-
我们需要做的就是在清单文件中添加此权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
-
并创建一个 LocationManager 实例,如下所示:
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
检查 GPS 是否启用。
-
然后实现LocationListener并获取坐标:
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
这是执行此操作的示例代码
/*---------- Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
}
}
catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
+ cityName;
editLocation.setText(s);
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)