java - Android检查位置权限错误

标签 java android location android-permissions android-gps

public class GPSService extends Service implements LocationListener  {


// saving the context for later use
private final Context mContext;

// if GPS is enabled
boolean isGPSEnabled = false;
// if Network is enabled
boolean isNetworkEnabled = false;
// if Location co-ordinates are available using GPS or Network
public boolean isLocationAvailable = false;

// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;

// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 30000;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;

// Declaring a Location Manager
protected LocationManager mLocationManager;

public GPSService(Context context) {
    this.mContext = context;
    mLocationManager = (LocationManager) mContext
            .getSystemService(LOCATION_SERVICE);

}

/**
 * Returs the Location
 *
 * @return Location or null if no location is found
 */
public void getLocation() {
    try {


        // Getting GPS status
        isGPSEnabled = mLocationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // If GPS enabled, get latitude/longitude using GPS Services
        if (isGPSEnabled) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
            if (mLocationManager != null) {
                mLocation = mLocationManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (mLocation != null) {
                    mLatitude = mLocation.getLatitude();
                    mLongitude = mLocation.getLongitude();
                    isLocationAvailable = true; // setting a flag that
                    // location is available
                    return;
                }
            }
        }

        // If we are reaching this part, it means GPS was not able to fetch
        // any location
        // Getting network status
        isNetworkEnabled = mLocationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isNetworkEnabled) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
            if (mLocationManager != null) {
                mLocation = mLocationManager
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (mLocation != null) {
                    mLatitude = mLocation.getLatitude();
                    mLongitude = mLocation.getLongitude();
                    isLocationAvailable = true; // setting a flag that
                                                // location is available
                    return;
                }
            }
        }
        // If reaching here means, we were not able to get location neither
        // from GPS not Network,
        if (!isGPSEnabled) {
            // so asking user to open GPS
            askUserToOpenGPS();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    // if reaching here means, location was not available, so setting the
    // flag as false
    isLocationAvailable = false;
}

/**
 * Gives you complete address of the location
 * 
 * @return complete address in String
 */
public String getLocationAddress() {

    if (isLocationAvailable) {

        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
        // Get the current location from the input parameter list
        // Create a list to contain the result address
        List<Address> addresses = null;
        try {
            /*
             * Return 1 address.
             */
            addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
        } catch (IOException e1) {
            e1.printStackTrace();
            return ("IO Exception trying to get address:" + e1);
        } catch (IllegalArgumentException e2) {
            // Error message to post in the log
            String errorString = "Illegal arguments "
                    + Double.toString(mLatitude) + " , "
                    + Double.toString(mLongitude)
                    + " passed to address service";
            e2.printStackTrace();
            return errorString;
        }
        // If the reverse geocode returned an address
        if (addresses != null && addresses.size() > 0) {
            // Get the first address
            Address address = addresses.get(0);
            /*
             * Format the first line of address (if available), city, and
             * country name.
             */
            /* Return the text */
            return String.format(
                    "%s, %s, %s",
                    // If there's a street address, add it
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "",
                    // Locality is usually a city
                    address.getLocality(),
                    // The country of the address
                    address.getCountryName());
        } else {
            return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it.";
        }
    } else {
        return "Location Not available";
    }

}



/**
 * get latitude
 * 
 * @return latitude in double
 */
public double getLatitude() {
    if (mLocation != null) {
        mLatitude = mLocation.getLatitude();
    }
    return mLatitude;
}

/**
 * get longitude
 * 
 * @return longitude in double
 */
public double getLongitude() {
    if (mLocation != null) {
        mLongitude = mLocation.getLongitude();
    }
    return mLongitude;
}

/**
 * close GPS to save battery
 */
public void closeGPS() {
    if (mLocationManager != null) {
        mLocationManager.removeUpdates(GPSService.this);
    }
}

/**
 * show settings to open GPS
 */
public void askUserToOpenGPS() {
    AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    mAlertDialog.setTitle("Location not available, Open GPS?")
    .setMessage("Activate GPS to use use location services?")
    .setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
            }
        })
        .setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                }
            }).show();
}

/** 
 * Updating the location when location changes
 */
@Override
public void onLocationChanged(Location location) {
    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
  }

   @Override
   public IBinder onBind(Intent arg0) {
    return null;
   }

}

在权限检查部分,我的应用程序每次都会崩溃...

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkSelfPermission(java.lang.String)' on a null object reference at android.content.ContextWrapper.checkSelfPermission(ContextWrapper.java:745) at com.example.fritzmaier.mysimplelistview.GPSService.getLocation(GPSService.java:72)

崩溃时间:

  if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
            }

最佳答案

使用 ActivityCompat 使用此权限检查

if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

关于java - Android检查位置权限错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49556717/

相关文章:

java - 谁能解释一下这段代码如何生成组合?

android - 经纬度返回 0,0

android - Fusionlocationprovider 在 android 中没有 gps 时无法工作

android - 试图获取 android 手机的更新位置,但代码给我带来了问题

java - 使用 Properties 动态读取/添加值到 conf 文件的参数

java - ORA-01461 : can bind a LONG value

java - com.parse.ParseObject 无法转换为

android - 手机处于纵向模式时感应 Action

android - 我无法编辑 android 模拟器的主机文件

android - 错误: cannot find symbol class ofArgb