April 29, 2019

Location Permission checking in Android

                        On this Blog I am going to explain about how to integrate Location Permission checking on your android application. Here is the steps,



Step 1 

        First we need to add the permission for Location Access. For this we need to add the following permissions on our applications AndroidManifest.xml file Here is the permissions we need to add, 

<uses-permission android:name="android.permission.INTERNET" />
<permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Step 2

New we are going to make a function checkLocationPermission() to check the location permission, This  function will return a Boolean value based on the location permission. If the user granted the permission it will return true otherwise it will return false and also it will request for the permission. Here is the function,

LOCATION_REQUEST_CODE
is one constant variable, On your application you can define your own value, I defiled this variable on my Constants.java Class file.

public static final int LOCATION_REQUEST_CODE = 4505;



private boolean checkLocationPermission() {
        boolean permission = false;
        try {
            if (ActivityCompat.checkSelfPermission(HomeActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                permission = true;
            } else
                ActivityCompat.requestPermissions(HomeActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, Constants.LOCATION_REQUEST_CODE);
        } catch (Exception e) {
        }
        return permission;
    }

Step 3

Now we need to check the permission on the  onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)  function. Which is a default function in Activity class.  Here is the Method,

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
    case Constants.LOCATION_REQUEST_CODE:
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // permission granted, Add your code after giving permission
       }else{
            //show some warning, or Add your code permission not granded
       }
        break;
     }









---------------
Thanks For Reading, Wish you a Happy Coding....





No comments:

Post a comment