我需要一个可以执行以下操作的简单代码 fragment 。 我需要一个可以执行以下操作的函数。
- 检查 GPS 是否启用。如果未启用,则启用它。
- 检查当前位置,即获取经度和纬度
- 禁用 GPS。
我不需要像 LocationListener 这样的连续位置更新。 15 分钟一次就可以了。 任何人都可以为此提供我的工作代码 fragment 吗?
最佳答案
启用 GPS:
private void turnGPSOn(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
用于禁用 GPS
private void turnGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
检查 GPS 是否打开。
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
用于获取当前位置。
public void getCurrentLocation() {
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
locationManager.requestLocationUpdates(provider, 1000, 0,
new LocationListener() {
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
System.out.println("WE GOT THE LOCATION");
System.out.println(lat);
System.out.println(lng);
getAddress();
}
}
}
});
}
关于android - 在 Android 上的 GPS 定位方面需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7536588/