为什么我的Android手机无法获得经纬度?

时间:2016-11-28 09:22:53

标签: android location latitude-longitude

我使用LocationManager获取当前位置,但我不能,为什么? 我已经添加了权限

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

以下是我的代码:

public class MainActivity extends Activity {

private TextView mLocation;
public LocationManager locationManager;
private String locationProvider;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mLocation = (TextView) findViewById(R.id.tv_location);
    getLocation();
}

private void getLocation() {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getProviders(true);
    if (providers.contains(LocationManager.GPS_PROVIDER)) {
        // 如果是GPS
        locationProvider = LocationManager.GPS_PROVIDER;
    } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
        // 如果是Network
        locationProvider = LocationManager.NETWORK_PROVIDER;
    } else {
        Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
        return;
    }
    // 获取Location
    Location location = locationManager.getLastKnownLocation(locationProvider);
    if (location != null) {
        // 不为空,显示地理位置经纬度
        showLocation(location);
    }else{
        // 监视地理位置变化
        locationManager.requestLocationUpdates(locationProvider, 0, 0,mListener);
    }

}

LocationListener mListener = new LocationListener() {
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onProviderDisabled(String provider) {
    }
    // 如果位置发生变化,重新显示
    @Override
    public void onLocationChanged(Location location) {
        showLocation(location);
    }
};

/** 显示地理位置经度和纬度信息 */
private void showLocation(Location location) {
    String locationStr = "维度:" + location.getLatitude() + "\n" 
            + "经度:"+ location.getLongitude();
    mLocation.setText(locationStr);
}

}

1 个答案:

答案 0 :(得分:0)

在Android 6和7中,访问该位置被视为必须在运行时请求的“危险权限”。

https://developer.android.com/training/permissions/requesting.html

您还可以在系统设置中授予该权限(应用&gt;您的应用&gt;权限)