Implement Runtime Permission For Location in Android Marshmallow

1 min read

Dear Friends

Now you have become experience android application developer. Congrats !. Need less to say if you want to use location services in your application you need to declare them in Android Manifest.xml as

 

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

 

Implementation

During android application development on Android 6.0 or above when you will be dealing with runtime permission, you will deal with a call back method which gets called by the system automatically whenever a permission made by application is allowed or denied by the user. Please have a look a below snapshot

pr_smart

 

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == 0) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            doYourWork()....
        }
    }
}

 

Now before this you need to request permission at runtime from user.

 

ActivityCompat.requestPermissions(ExchangeActivityNov.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, 
        Manifest.permission.ACCESS_FINE_LOCATION}, 0);

 

Android Studio will give you some compilation error  so you can protect the code as

if (ContextCompat.checkSelfPermission(ExchangeActivityNov.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(ExchangeActivityNov.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, 
   Manifest.permission.ACCESS_FINE_LOCATION}, 0);
} else {
// doYourCoolThing
}

 

So if user has previously provided permission  you will not enter into if block and you will  directly go to else part and do you cool thing.

Also please ensure to work with Android Runtime permission your compileSDKversion in gradle should be 23 or higher and your targetSDKversion should be 23 or higher.

 

if you have any question related to blog or and suggestion please visit the google form and post your query.

https://docs.google.com/forms/d/1pYAZUoGKSi6rFl5zi28GUuWV3ifngWVKLTPjldzs-Q4/viewform

 

Code Reference :

Task2New

 

 

Happy Coding.