每次用户打开应用程序时,我们都会检查是否有他当前的位置。如果没有,该应用会要求他在LocationManager
中启用位置并返回应用。问题:有时,在某些手机中,即使在启用该位置并且用户返回应用后,该位置仍为null
。所以用户陷入了困境。为什么位置仍为空?我该怎么办?
String locationContext = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(locationContext);
Location location = locationManager.getLastKnownLocation(locationProvider);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
final String lat = String.valueOf(latitude);
final String lon = String.valueOf(longitude);
System.out.println("Localisation: " + lat + " " + lon);
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String id = preferences.getString("id", null);
new sendLocation().execute(id, lat, lon);
} else {
System.out.println("NO LOCATION!!");
AlertDialog.Builder alert = new AlertDialog.Builder(Home.this);
alert.setTitle("Get started");
alert.setMessage("We need your location to detect places nearby. Please enable -Wireless Networks- in your location settings to get started.");
// Set an EditText view to get user input
final TextView input = new TextView(Home.this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
答案 0 :(得分:0)
当用户在手机中启用位置功能时,Android设备不一定会自动刷新位置信息。
为了保证您获得某种位置,您需要为单个或多个更新注册LocationListener
。
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0.0f, this);
在您的主要课程“this”中,添加implements LocationListener
,并添加以下方法:
public void onLocationChanged(Location location) {
//This "location" object is what will contain updated location data
//when the listener fires with a location update
}
public void onStatusChanged(String provider, int status, Bundle extras) {
//Required by LocationListener - you can do nothing here
}
public void onProviderEnabled(String provider) {
//Required by LocationListener - you can do nothing here
}
public void onProviderDisabled(String provider) {
//Required by LocationListener - you can do nothing here
}
当您获得位置更新时,您可以通过以下方式禁用侦听器:
locationManager.removeUpdates(this);
此处有关LocationListener的更多文档: http://developer.android.com/reference/android/location/LocationListener.html