Albin Åberg
Albin Åberg

Reputation: 39

LocationManager checkPermission

So my problem is quite simple and it is that I have no clue how I would implement the checkPermission into this code. I have read up on it but I can't still quite wrap my head around it. One of my problems is that some examples want me to point towards an activity but that does not work.

The line where I request location updates throws SecurityException and wants me to do checkPermission.

Code examples and/or explanations would make me very grateful.

And excuse me before hand if my explanation is lacking, I'm quite bad at that part!

public class LocationHandler implements LocationListener {
private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager mLocationManager;

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

    //Check Permission
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
        MIN_TIME_BW_UPDATES,
        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}

@Override
public void onLocationChanged(Location location) {

    String msg = "New Latitude: " + location.getLatitude()
            + "New Longitude: " + location.getLongitude();

    Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();

}

@Override
public void onProviderDisabled(String provider) {

    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    mContext.startActivity(intent);
    Toast.makeText(mContext, "Gps is turned off!! ",
            Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderEnabled(String provider) {

    Toast.makeText(mContext, "Gps is turned on!! ",
            Toast.LENGTH_SHORT).show();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}
}

Upvotes: 0

Views: 861

Answers (2)

nge
nge

Reputation: 116

Here is some code that might help.

You will need to wrap the location request with try/catch for security exceptions.

Add to strings.xml:

<string name="location_permission_rationale">"Location permission is needed for providing nearby services."</string>

Import this:

import static android.Manifest.permission.ACCESS_FINE_LOCATION;

Needed in your activity class and LocationHandler

/**
 * Id to identity LOCATION permission request.
 */
private static final int REQUEST_LOCATION = 0; 

...

Override in your activity class:

/**
 * Callback received when a permissions request has been completed.
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode == REQUEST_LOCATION) {
        if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // You can request location here and update your vars
        }
    }
}

Add this to your LocationHandler class and call from the constructor. If it returns true, you are gtg. If it returns false then you'll have to do your location updates in the callback.

private boolean requestLocationPermission() {

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    if (checkSelfPermission(mContext, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        return true;
    }

    if (shouldShowRequestPermissionRationale((Activity)mContext, ACCESS_FINE_LOCATION)) {

        Snackbar.make(((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content),
                ((Activity)mContext).getResources().getString(R.string.location_permission_rationale), Snackbar.LENGTH_INDEFINITE)
                .setAction(android.R.string.ok, new View.OnClickListener() {
                    @Override
                    @TargetApi(Build.VERSION_CODES.M)
                    public void onClick(View v) {
                        requestPermissions((Activity)mContext, new String[]{ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
                    }
                });
    } else {
        requestPermissions((Activity)mContext, new String[]{ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
    }
    return false;
}

Upvotes: 1

Delta Enlightment
Delta Enlightment

Reputation: 1

It seems you may have forgotten to add these two permissions in the manifest.

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

Upvotes: 0

Related Questions