朋友们,我遇到了麻烦,我想在不使用GPS的情况下找到我当前的位置,有人可以帮助我..
以下是我的代码,但无效
public Location getLocation() {
Location location = null;
final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
try {
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//updating when location is changed
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.i("latitudelongitude", longitude + "," + latitude);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isNetworkEnabled && !isGPSEnabled) {
//在这种情况下,在onResume方法中再次调用getLocation // startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
} else {
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
//请求访问精细位置
ActivityCompat.requestPermissions(this,new String [] {android.Manifest.permission.ACCESS_FINE_LOCATION},1);
//在授予回调权限的情况下再次调用getLocation函数
} enter code here
返回地点;
}