Runtime permission in Android

In my last tutorial, We had practiced awesome features of RxJava in Android. Here are the link details RxJava in android part1, RxJava in android part2 and MVP with RxJava.

Today we got one more day to learn something more. Let's make this day more awesome to learn something new. In this article, we will learn why runtime permission and how to give permission at runtime in the application. Earlier we have practiced that the user can be seen the permission detail at while installing the app. But in marshmallow device version 6.0 it has changed. Now application will not be granted the permission while installing the application. It will ask users at runtime. Why this is required? 

In the previous below the marshmallow versions like the lollipop and other lower version devices, User was felt like obvious to see the permission details while installing that, They might be thinking that why can I shared my confidential information without asking that permission. The application should be asked me, hey if you want to access those then please grant me permission to access. For example, if any other app wants to get access the phone contact then user feel obvious to give access those. That why it comes runtime permission. If the other application wants to access phone contact of users then its all depend on the user if they granted the permission or not. If the user has not granted then other application will not be allowed to access that information.

One common question of every developer that how android take care our old application launch on marshmallow device. So I would say do not panic be relaxed android take care that issue very smartly. If your application has built on targetsdkversion is less than 23 then it should not be crashed on Android M. It will work fine without any issue. Runtime permission will only ask users if you build the app on target SDK version 23 or higher. 

This really sounds good for the users to feel confidence that my phone is secure if I used to install any other application without any issue. Android take care security point of view at the top priority. Awesome:)

Okay, Let's see what are those permissions is granted while installing the application. These permissions called protection-level permission. It will not ask the user at runtime.


Great. This permission is required to add in Android manifest file then it works fine without any crash. Now let's check what are required to check the permission if my target SDK version and compile SDK version is 23 or higher.

A developer needs to follow three basic methods.
1. checkSelfPermission(Permission) - to check the permission is already granted or not.
2. requestPermissions(String [] permissions, int requestCode) - if not then request for permission
3. onRequestPermissionsResult(int premsRequestCode, String [] permissions, int [] grantResults) - to check the result whether permission is granted or not.

Let's see one example I am building an app which targets SDK version is 23 or higher. I want location access in one of my application. First of all, you need to know what are permission is required for access the Location. Okay, How do I make sure? Let's check in framework level what Gooogle has defined for location access?
When I look this file in framework module.
I found this permission is required to access the location.

 private static final Set<String> LOCATION_PERMISSIONS = new ArraySet<>();
109    static {
110        LOCATION_PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION);
111        LOCATION_PERMISSIONS.add(Manifest.permission.ACCESS_COARSE_LOCATION);
112    }

So basically these two permission is required to access Location. Ok, Let's check while clicking on a button I want to access the location.

import android.Manifest;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import com.sunil.mvprxjavaapp.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

 * Created by sunil on 08-04-2017.

public class RunTimePermissionTestActivity extends AppCompatActivity {

    Button RuntimeButton;

    protected void onCreate(@Nullable Bundle savedInstanceState) {


    public void RunTimeClick(){

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted or not
            } else {
                //Request Location Permission
        else {
           // not required any runtime permission for below M

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void askLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission. This info convince to users to allow
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown to ask for permission again
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );

            } else {
                // No explanation needed, we can request the permission.
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );

    private void tryToGetLocationValue() {
        Toast.makeText(this, "Good to go to fetch location", Toast.LENGTH_LONG).show();

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission is granted
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {


                } else {

                    // permission denied
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();


Add this line in Android Manifest file.

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

Great You did well. It does not require to check permission for both ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION. Android document said you can allow only one permission is enough for access but need to add both permissions in the android manifest file.

You can see about snaps, It will ask for the user to allow or deny. If a user has denied press and again he tries to access location while clicking on the button it prompts to the user to need permission access to user location functionality. Then this time prompts shows with check box never ask again. If the user has checked this box it means user not interested in allowing this permission and not interested in using location feature anymore.

Thanks for reading this post.


  1. Hi, I read your blog this is very informative. Thanks for share this blog. You can find dedicated Web designers,Mobile Application Developers,Ecommerce Solution, SEO and marketing specialists will tailor make the solution you want for your business.Know more about click here –

  2. Hai Author Good Information that i found here,do not stop sharing and Please keep

    updating us..... Thanks

    1. Thanks Vamshi, I will keep updating and thanks for appreciation.


  3. Wonderful blog.. Thanks for sharing informative Post. Its very useful to me.

    Installment loans
    Payday loans
    Title loans

  4. Sap Training Institute in Noida-Webtrackker is the best SAP training institute in noida. SAP is drastically a completely state-of-the-art element ever to analyze and to excel in it. However with the ever-growing price, and being the most accessible organization solution key, agencies are greater involved to have their employees specialized in it. The education courses effectively deliver you with the fundamental recognition of SAP, in a grade by grade way.
    Sas Training Institute in Noida
    PHP Training Institute in Noida
    Hadoop Training Institute in Noida
    Oracle Training Institute in Noida
    Linux Training Institute in Noida
    Dot net Training Institute in Noida

  5. Air conditioning maintenance birmingham- onlyrepaircenter has the 30 Years Experience in Air conditioning maintenance service in birmingham. If you are facing the problem in your air conditioning of any company such as Daikin, Mitsubishi, Carrier, Fujitsu, Toshiba, Airedale, Sanyo, Trane and LG then you can contact to us.

    Air Conditioning Installation birmingham
    Commercial air conditioning repair Birmingham
    residential air conditioning repair birmingham
    Air Conditioning Maintenance birmingham
    window ac repair birmingham

  6. Best Php Training Institutes in Noida - PHP training in itself is an incredible choice for each person who's trying to decorate his career opportunities in the end. It helps you understand greater approximately distinctive database practical specifications.

    Best Php Training Institutes in Noida

    Best Digital Marketing Training Institutes in Noida

    Best Hadoop Training Institutes In Noida

    Best Sas Training Institutes in Noida

    Best Sap Training Institutes in Noida

    Best Linux Training Institutes in Noida

    Best Salesforce Training Institutes in Noida

  7. Australia Best Tutor is offering assignment help Services for all universities learners or students at an affordable price. Here All students are joining for best grades and better results.

    Visit Here

    Australia Best Tutor
    Sydney, NSW, Australia
    Call @ +61-730-407-305
    Live Chat @

    Our Services

    Online assignment help
    my assignment help
    assignment help
    help with assignment
    instant assignment help
    Assignment help Services

  8. NayHoh,

    Great info! I recently came across your blog and have been reading along.
    I thought I would leave my first commentI don’t know what to say except that ,I did this for the original version of HyperLynxDRC, I called my routine snappy.

    This example is in AATK>HyperLynxDRC\Working\Violations

    Function snappy(Row, Path)
    ' Create the required objects
    Set objSnagit = CreateObject("SNAGIT.ImageCapture.1")
    Set wshShell = CreateObject("WScript.Shell")
    ' Set input options
    objSnagit.Input = siiDesktop
    objSnagit.IncludeCursor = True
    ' Set output options
    objSnagit.Output = sioFile
    objSnagit.OutputImageFile.FileType = siftPNG
    objSnagit.OutputImageFile.ColorDepth = sicd32Bit
    objSnagit.OutputImageFile.FileNamingMethod = sofnmFixed
    objSnagit.OutputImageFile.FileName = Row '"snagtest"
    objSnagit.OutputImageFile.Directory = Path '"C:\"
    ' Capture
    Call add_pic(Row, Path)
    ' Launch the captured image in the default viewer
    'wshShell.Run "C:\snagtest.png", 0, False
    ' Release the objects
    Set objSnagit = Nothing
    Set wshShell = Nothing
    End Function
    Great effort, I wish I saw it earlier. Would have saved my day :)

    Thank you,


  9. To improve Knowledge about the latest and vital technology would increase one's self esteem to the core at the time of lagging confidence.The content presented here is quite resembling the same. You have done a great job by sharing this in here.
    sap abap online training in usa


Debug Database in Android

In my last tutorial, we have learned how we can use persistence database in android. We also understood which database wrapper we can use...

Contact Me


Email *

Message *