位置始终返回null

时间:2018-06-08 14:22:09

标签: android gps location android-developer-api

我正在尝试查找我的设备位置,但它始终返回null。 以下是我的代码。

    public Location getLocation() {

    if (ContextCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(context, "Permission is not granted", Toast.LENGTH_LONG).show();
        return null;
    }
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    assert locationManager != null;
    boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (isGPSEnabled) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 10, this);
        return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    } else {
        Toast.makeText(context,"Please enable GPS",Toast.LENGTH_LONG).show();
    }
    return null;
}

0 个答案:

没有答案
相关问题