Android MapActivity cannot retrieve location data
I have followed the HelloMapView tutorial for android, and added some code to capture my current location information and display in a textview.
I have tested these code in another program and it worked, it is able to display my longitude and latitude data when the launch that app. However when i copied the code into this MapActivity, it seems that i cannot get the location data.
Here's part of the code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.androidmarker);
itemizedOverlay = new HelloItemizedOverlay(drawable, this);
Button button1 = (Button)this.findViewById(R.id.button1);
tv1 = (TextView) this.findViewById(R.id.textView1);
button1.setOnClickListener(mScan);
latitude = 1.3831625;
longitude = 103.7727321;
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
if (System.currentTimeMillis() - location.getTime() < 3000)
{
longitude = location.getLongitude();
latitude = location.getLatitude();
tv1.setText(Double.toString(longitude));
}
}
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 10, locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
tv1.setText(Double.toString(latitude));
}
开发者_Python百科 @Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
Did you added proper permissions in Manifest? Like this
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Also please check your gps is enabled or working on ur deive.
精彩评论