我正在尝试获取android中的当前位置,因为我已经使用了android并且以下是我的代码
locationManager = (LocationManager) getSystemService(this.context.LOCATION_SERVICE);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(true);
crta.setBearingRequired(true);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
Log.d("","provider : "+provider);
provider = LocationManager.GPS_PROVIDER;
Log.d("","provider : "+provider);
locationManager.requestLocationUpdates(provider, 0, 0, (LocationListener) this);
Location location = locationManager.getLastKnownLocation(provider);
//isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (location != null)
{
double latitude = location.getLatitude();
double longitude = location.getLongitude();
txtLat.setText("Latitude"+latitude+"longitude"+longitude);
Log.d("not null", "location is not null");
}
else
{
Toast.makeText(getApplicationContext(), "locatyion is null", Toast.LENGTH_LONG).show();
Log.d("null","location is null");
}
问题是当我打开应用程序时,它不会给我当前位置的位置为空。有人可以帮忙吗?我见过很多例子并尝试了其他例子,但没有奏效。 我添加了
if (!isNetworkEnabled)
{
Toast.makeText(getApplicationContext(), "No network provider the gps wont work", Toast.LENGTH_LONG).show();
// no network provider is enabled
}
else{
Toast.makeText(getApplicationContext(), "Network is available", Toast.LENGTH_LONG).show();
}
并且它说gps可用且网络不可用
答案 0 :(得分:0)
代码需要与位置更改的侦听器的广播接收器异步...
发生这种情况是因为GPS需要一些时间来提供位置,当它第一次启动时,一切都是null
。
请参阅以下代码:
public class Example extends Activity implements LocationListener {
LocationManager mLocationManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
// Do something with the recent location fix
// if it is less than two minutes old,
// otherwise wait for the update below
}
}
public void onLocationChanged(Location location) {
if (location != null) {
Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
// You need to call this whenever you are done:
// mLocationManager.removeUpdates(this);
}
}
// Required functions
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String arg0) {}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}
更多here