【发布时间】:2014-12-02 12:05:48
【问题描述】:
在我的应用程序中,我将检查 GPS 是否启用。如果未启用,我会将页面重定向到 GPS 设置。
启用 GPS 后,我将从 LocationManager 获取位置。但是我找不到位置。
在这里我附上了我的代码。
if (isGPSEnabled())
{
getLocation();
}
private boolean isGPSEnabled() {
boolean gpsEnabled = false;
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
gpsEnabled = true;
return gpsEnabled;
} else {
showGPSDisabledAlertToUser();
}
return gpsEnabled;
}
private void showGPSDisabledAlertToUser() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder
.setMessage(
"GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void getLocation() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
} else {
}
}
public void onLocationChanged(Location location) {
Double lat = (Double) (location.getLatitude());
Double lng = (Double) (location.getLongitude());
}
请告诉我我犯了什么错误?
提前谢谢..
【问题讨论】:
-
你是用真机还是安卓模拟器测试?如果您使用的是设备,它是哪一个?还要记住,GPS 在室内效果不佳,如果您在室外或靠近窗户的地方尝试可能会更好(我过去也遇到过类似的情况)。但是,LastKnownLocation 策略应该如您所说。
-
愿此链接对您有所帮助stackoverflow.com/questions/4772686/…
-
我犯了什么错误??我认为每件事都是正确的。当我尝试在不使用 GPS 启用方法的情况下运行我的应用程序时(我隐藏了该方法,并且我手动在 GPS 上),它正在工作。当我尝试添加 GPS 启用方法时,位置未显示..