// get current location
private Location getMyLocation() {
if (locationManager
.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 100, 0, this);
.isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);//這個只要手機聯網百分之百能獲取到
c.setAccuracy(Criteria.ACCURACY_FINE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(c, true);
Location location = locationManager
.getLastKnownLocation(provider);
if (location != null) {
return location;
}
} else {
Toast.makeText(getActivity(), "請連接網絡", Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(getActivity(), "請打開GPS開關", Toast.LENGTH_LONG).show();
}
return null;
}
//上面的獲取可能爲null,下面的絕對不會爲null,前提是手機聯網
@Override
public void onLocationChanged(Location location) {
if (location != null) {
myLocation = location;
LogUtils.i("myLocation-changed", "lat:" + myLocation.getLatitude()
+ "lng:" + myLocation.getLongitude());
}
}