此代码非常适用于 GPS:
public class GetLocation extends Activity implements LocationListener {
LocationManager lm;
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_mission);
// Acquire a reference to the system Location Manager
tv= (TextView)findViewById(R.id.locationOutput);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, this);
}
public void onLocationChanged(Location arg0) {
String lat = String.valueOf(arg0.getLatitude());
String lon = String.valueOf(arg0.getLongitude());
Log.e("GPS", "location changed: lat="+lat+", lon="+lon);
tv.setText("lat="+lat+", lon="+lon);
}
public void onProviderDisabled(String arg0) {
Log.e("GPS", "provider disabled " + arg0);
}
public void onProviderEnabled(String arg0) {
Log.e("GPS", "provider enabled " + arg0);
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
Log.e("GPS", "status changed to " + arg0 + " [" + arg1 + "]");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_get_mission, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
但是我想从网络而不是 GPS 获取位置。所以我改变:
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, this);
到
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
然后我什么也得不到。这是由于代码中的错误,还是位置没有像 GPS 那样频繁更改,因此永远不会调用 onLocationChange?如果我想在此时查看位置而不进行更改,我应该.getLastKnownLocation
在哪里调用它,以便在应用程序启动时更新?