我试图从下面的代码中获取当前位置。但它无法正常工作。我无法找到问题。当它在模拟器上部署时,它显示goolemaps无法正常工作。当它在设备上部署时,它显示强制关闭。任何人都可以帮助我吗?
package com.example.googlemaps;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
public class GoogleMapsActivity extends MapActivity implements LocationListener {
private LocationManager locManager;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//fetch the map view from the layout
MapView mapView = (MapView) findViewById(R.id.mapview);
//make available zoom controls
mapView.setBuiltInZoomControls(true);
// invalidate the map in order to show changes
mapView.invalidate();
// Use the location manager through GPS
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
//get the current location (last known location) from the location manager
Location location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//if location found display as a toast the current latitude and longitude
if (location != null) {
Toast.makeText(
this,
"Current location:\nLatitude: " + location.getLatitude()
+ "\n" + "Longitude: " + location.getLongitude(),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Cannot fetch current location!",
Toast.LENGTH_LONG).show();
}
//when the current location is found – stop listening for updates (preserves battery)
locManager.removeUpdates(this);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
/* When the activity starts up, request updates */
@Override
protected void onResume() {
super.onResume();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
@Override
protected void onPause() {
super.onPause();
locManager.removeUpdates(this); //activity pauses => stop listening for updates
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}