1. 程式人生 > >Android Gps定位和網路定位

Android Gps定位和網路定位

private LocationManager lm;
private String provider;
private LocationListener locationListener;

在oncreate();
lm= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
private void updataLocation() { List<String> list = lm.getProviders(true); if (list.contains(LocationManager.GPS_PROVIDER
)) { provider = LocationManager.GPS_PROVIDER; } else if (list.contains(LocationManager.NETWORK_PROVIDER)) { provider = LocationManager.NETWORK_PROVIDER; } else { Toast.makeText(this, "請檢查網路或GPS是否開啟", Toast.LENGTH_LONG).show(); return; } Location location = lm
.getLastKnownLocation(provider); if (location != null) { String string = "緯度為:" + location.getLatitude() + ",經度為:"+ location.getLongitude(); XLog.d("puchunjie",string); } locationListener=new LocationListener() { @Overridepublic void onLocationChanged(Location location) { } @Override
public void onStatusChanged(String provider, int status, Bundle extras) { } @Overridepublic void onProviderEnabled(String provider) { } @Overridepublic void onProviderDisabled(String provider) { } }; lm.requestLocationUpdates(provider,2000,2, locationListener);}
在destroy裡面()
if (lm != null) {
    lm.removeUpdates(locationListener);
}