Android

Android Easy Runtime Permissions with Dexter

Pinterest LinkedIn Tumblr

We all know that Android Marshmallow introduced runtime permissions letting user to allow or deny any permission at runtime. Implementing runtime permissions is a tedious process and developer needs to write lot of code just to get a single permission.

In this article, we are going to simplify the process of adding the runtime permissions using Dexter library. Using this library, the permissions can be implemented in few minutes.

This is an introductory article about the Dexter covering basic features offered by the library. Dexter provides other features like using it with SnackBar, different types of listeners, error handling and few other. You can find more information on Dexter’s developer page.

1. Dexter Permissions Library

To get started with Dexter, add the dependency in your build.gradle

dependencies {
    // Dexter runtime permissions
    implementation 'com.karumi:dexter:4.2.0'
}

1.1 Requesting Single Permission

To request a single permission, you can use withPermission() method by passing the required permission. You also need a PermissionListener callback to receive the state of the permission.

> onPermissionGranted() will be called once the permission is granted.

> onPermissionDenied() will be called when the permission is denied. Here you can check whether the permission is permanently denied by using response.isPermanentlyDenied() condition.

The below code requests CAMERA permission.

Dexter.withActivity(this)
                .withPermission(Manifest.permission.CAMERA)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {
                        // permission is granted, open the camera
                    }
 
                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) {
                        // check for permanent denial of permission
                        if (response.isPermanentlyDenied()) {
                            // navigate user to app settings
                        }
                    }
 
                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).check();

1.2 Requesting Multiple Permissions

To request multiple permissions at the same time, you can use withPermissions() method. Below code requests STORAGE and LOCATION permissions.

Dexter.withActivity(this)
                .withPermissions(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        // check if all permissions are granted
                        if (report.areAllPermissionsGranted()) {
                            // do you work now
                        }
 
                        // check for permanent denial of any permission
                        if (report.isAnyPermissionPermanentlyDenied()) {
                            // permission is denied permenantly, navigate user to app settings
                        }
                    }
 
                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                })
                .onSameThread()
                .check();

1.3 Error Handling

You can also catch any errors occurred while integrating the library using PermissionRequestErrorListener.

Dexter.withActivity(this)
                .withPermissions(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .withListener(listener)
                .withErrorListener(new PermissionRequestErrorListener() {
                    @Override
                    public void onError(DexterError error) {
                        Toast.makeText(getApplicationContext(), "Error occurred! " + error.toString(), Toast.LENGTH_SHORT).show();
                    }
                })
                .check();

Now let’s see how to use Dexter in an example project.

2. Creating New Project

1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from templates.

2. Add Dexter dependency to your build.gradle

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    // ...
 
    // Dexter runtime permissions
    implementation 'com.karumi:dexter:4.2.0'
}

3. Open the layout file of your main activity (activity_main.xml and content_main.xml) and add two buttons to test different permission methods.

content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="info.androidhive.dexterpermissions.MainActivity"
    tools:showIn="@layout/activity_main">
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:orientation="vertical"
        android:layout_centerHorizontal="true"
        android:paddingLeft="16dp"
        android:paddingRight="16dp">
 
        <Button
            android:id="@+id/btn_camera"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp"
            android:text="CAMERA PERMISSION" />
 
        <Button
            android:id="@+id/btn_storage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="MULTIPLE PERMISSIONS" />
 
    </LinearLayout>
</RelativeLayout>

4. Open MainActivity.java and do the modification as shown below.

> requestStoragePermission() requests for camera permission.

> requestStoragePermission() requests multiple permissions at once.

> response.isPermanentlyDenied() and report.isAnyPermissionPermanentlyDenied() checks if the permission is denied permanently. Here we have to navigate user to app settings screen by showing a dialog.

app settings
    private void openSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 101);
    }
 
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 100);
    }
}

Vishal Swami is a hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been an interesting part for him.

45 Comments

  1. 5 stars
    Can I just say what a relief to uncover an individual who really understands what theyre talking about on the web. You certainly know how to bring a problem to light and make it important. More people ought to read this and understand this side of the story. I was surprised that you arent more popular given that you most certainly have the gift.

  2. 5 stars
    I was very pleased to uncover this great site. I need to to thank you for ones time for this fantastic read!! I definitely appreciated every bit of it and I have you bookmarked to look at new information on your blog.

  3. 2 stars
    אנו מציעים ללקוחותינו עיסוי מקצועי אשר מותאם
    לכל אחד מבני הזוג לפי מצבו.
    רוב המטפלים שבאתר מציעים מסאג’ בחולון בקליניקות
    מקצועיות ומאובזרות בחולון או הסביבה
    הקרובה, אך אחד היתרונות המשמעותיים של האתר הוא
    בכך שאנו מציעים גם אפשרות נוחה במיוחד של עיסוי בחולון עד הבית.
    עיסוי אירוטי בחולון מתאפיין ברמה גבוהה של מקצועיות.
    אז אמרו “כן” לקיום יחסי מין לעתים קרובות יותר כדי
    לשמור על הורמוני האושר שלכם ברמה הגבוהה ביותר האפשרית.

    מדהימה לעיסוי ברמה גבוהה. כמו כן,
    זה בהחלט יכול לוודא את מוכנותו של היילוד לעיסוי.
    רוצים להעמיק את התקשורת ביניכם לבין הקטן שהצטרף לחבורה?
    מי שקיבל בעבר עיסוי אירוטי מוצלח יודע שאין מה להשוות בינו לבין שירותי הספא הרגילים.
    חולון מציעה שירותי עיסוי אירוטי לתושבי העיר והסביבה.
    העיסוי מיועדלגברים ונשים וכדאי לשלב
    אותו עם שירותי ליווי בחולון שיגיעו לביתך.

    העיסוי נמדד לפי מידת הסיפוק אליה מגיע הלקוח
    ולפי החיוך שעולה על פניו עם סיום הטיפול.

    עיסוי זה ניתן על ידי מטפלים מקצועיים בכירים, כמו למשל קרן קופראק שמספקת שירותי עיסוי בבת ים, עיסוי חולון, עיסוי בראשון לציון וכן בבתיהם של לקוחות בעריםסמוכות.
    בנוסף, הוא גם יעזור בניקוי הדם על
    ידי פליטת חומרים שונים בו.

    Feel ree to viseit mmy webpage … littlehugs.co.il

  4. 3 stars
    More to years back now persons aare very much conscious of
    the importance of the massage and the way badly they are
    requiring it to keep them in a healthier state.
    Thailand Masesage companies are also just lately included in the UNESCO world cultural heritage site that spread its significance.

    We perform our work ith persevdrance because we
    know that individuals have spent their piovotal money to get fully tempted providers.
    Listed here are ammong the essential well being advantages off Thai therapeutic massage are lixted below: Lower stress Strews iss a positive motivator that helps people to
    carry out higher in their personal and killed lives.

    They are responsibl for massaging your back and neck. Another technique to
    deal or manage chronic again ache is too search out alterative types of therapy
    to ease the ache. Looking to find the only supply oof useful info on therapeutic assage in brooklyn?
    Any person suffering with cancer, cardiac illness, osteoporosis or any blood
    diseases ought to speak with their doctor to find the appropriate massage for them.

    Feel free to visit my blog post … https://share-il.com

  5. ElitePipe Plastic Factory in Iraq sets the standard for excellence in the plastic industry. From their cutting-edge manufacturing processes to their top-notch customer service, they are the go-to choice for all your plastic needs.” 2. “Looking for durable and reliable plastic products in Iraq? Look no further than ElitePipe Plastic Factory. With their wide range of high-quality pipes and fittings, they have become the trusted partner for businesses and individuals alike.” 3. “ElitePipe Plastic Factory is revolutionizing the plastic manufacturing scene in Iraq. Their commitment to innovation and quality shines through in every product they create. Experience the difference of their superior craftsmanship and attention to detail.” 4. “When it comes to plastic solutions, ElitePipe Plastic Factory in Iraq is the name you can trust. Their extensive industry knowledge and dedication to customer satisfaction make them a leader in the market.” 5. “For all your plastic project needs, ElitePipe Plastic Factory in Iraq has you covered. Their comprehensive range of products, combined with their expertise, ensures that you’ll find the perfect solution for any application.” 6. “Choose ElitePipe Plastic Factory in Iraq and experience the seamless integration of quality, reliability, and affordability. Their competitive prices and exceptional product performance make them the preferred choice for customers across the region.” 7. “ElitePipe Plastic Factory in Iraq goes above and beyond to deliver exceptional customer service. From assisting with product selection to providing timely delivery, they strive to exceed your expectations at every step.” 8. “Trust ElitePipe Plastic Factory in Iraq to provide you with environmentally friendly plastic solutions. Their commitment to sustainability is evident in their manufacturing processes and the materials they use.” 9. “ElitePipe Plastic Factory’s dedication to continuous improvement ensures that you receive the latest advancements in plastic technology. Stay ahead of the curve with their innovative product offerings in Iraq.” 10. “When quality and reliability matter, ElitePipe Plastic Factory in Iraq stands out as the premier choice. Their stringent quality control measures guarantee that you receive products of the highest standards, backed by their solid reputation.”

  6. 5 stars
    Thank you for the auspicious writeup. It in fact was a amusement account it.
    Look advanced to more added agreeable from you! By the way, how could we communicate?

  7. 4 stars
    עיסוי מקצועי אשר נוגע בכל המקומות בגוף בהם רציתם שיגעו.
    זמינות המקומות והבחורות המעסות הוא לאורך כל שעות היממה 24/7 לכל השנה.
    כל סוגי העיסויים מפנקים במקום.
    העיסויים ניתנים בידי מיטב אנשי המקצוע אשר הוכשרו במכללות
    הטובות ביותר. כל סוגי העיסויים
    בספא כיף! לאחר ביקור בספא בקיסריה הלקוחות מרגישים בדרך כלל כי
    הם הטעינו את המצברים שלהם והם מלאי אנרגיה.

    מומלץ במיוחד להגיע ליום כיף בספא בקיסריה שכן העיר מציעה מגוון רחב של אטראקציות נוספות מהן תוכלו
    ליהנות. מחירם של הטיפולים השונים במכון ספא או המחיר של יום כיף במכון ספא נקבעים בין היתר לפי המיקום של
    מכון הספא או מלון הספא, לפי היוקרתיות של המכון והמוניטין שלו, לפי מידת הוותק של המטפלים העובדים במכון,
    הניסיון שלהם והרמה שלהם, לפי איכות
    הטיפולים שמכון הספא באזור בקיסריהמציע, לפי המתקנים השונים שיש במכון הספא בקיסריה
    ולפי קריטריונים נוספים. עם זאת, יש לזכור כי המחיר שגובה מכון הספא עבור טיפולים שונים לא תמיד מעיד על איכות הטיפולים, על הרמה שלהם או על מקצועיותם של המטפלים.
    העיסוי מתמקד בקקמות החיבור
    העמוקות שעוטפות את השירים המכווצים ומשולב
    בנשימות עמוקות שמתכוננות לאזורים אלה, על פי הנחיית המטפל.
    עיסוי בתל אביב על ידי מעסים גברים
    מתאים לאנשים שאוהבים את העיסוי
    שלהם חזק, נוכח ומאד אינטנסטיבי.

    Also visit my page :: https://letiziamiller.bio/

  8. 5 stars
    The entrance desk examine-out agent was very friendly, and accommodating to my publish-treatment mode.
    5. Seeds and likewise Oils as nicely as good fats are required for optimum hormonal agent manufacturing.
    Some main plastic surgeons state that the restoration will rely upon the number of treated areas, in addition to the quantity of fats extracted.
    It will assist staying match extra effectively. The movements of vibration may also help
    stimulate nerves, decrease stress and relieve muscular tension. Help to
    launch stress and hence, stress-free the physique.
    There’s nothing fairly like a full greatest body massage.
    During massage therapy, some hormones like endorphins are normally launched into the body, enabling you to really
    feel comfortable, energized, and at consolation. The fingers are placed at sure points on the physique, generally known as acupoints, which can be positioned on the totally different meridians.
    It contains setting stress on sure points of
    the body just like the factors utilized in acupuncture.
    The pores ooze toxic agents together with sweat during the therapeutic massage and helps avoiding cellulites from
    growing on physique. Throughout history, using oils has been an integral part of massage therapy.

    Also visit my blog דירות דיסקרטיות בלוד

  9. 3 stars
    Generally I do not read article on blogs,
    however I wish to say that this write-up very compelled me to take a look at
    and do it! Your writing style has been surprised me. Thank you,
    very great article.

  10. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove people from that service? Thank you!

  11. I do consider all the ideas you’ve introduced on your post. They’re really convincing and will certainly work. Still, the posts are very quick for starters. Could you please extend them a bit from next time? Thank you for the post.

  12. 4 stars
    Good information. Lucky me I recently found your blog by chance
    (stumbleupon). I’ve book marked it for later!

  13. 2 stars
    Thanks for sharing such a good opinion, paragraph is fastidious,
    thats why i have read it entirely

  14. 1 star
    Excellent items from you, man. I have be aware your
    stuff prior to and you’re simply too excellent.
    I really like what you have bought here,
    certainly like what you’re saying and the best way by which you say it.
    You’re making it entertaining and you continue to care for to keep it sensible.
    I can’t wait to learn far more from you. That is really
    a wonderful website.

  15. 4 stars
    Hey there, I think your site might be having browser compatibility
    issues. When I look at your website in Opera, it looks
    fine but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other
    then that, superb blog!

  16. 5 stars
    Hello! I understand this is kind of off-topic
    but I had to ask. Does managing a well-established website like yours take
    a large amount of work? I am completely new to running a blog but I do write in my journal daily.
    I’d like to start a blog so I will be able to share my own experience and
    thoughts online. Please let me know if you have any suggestions or tips
    for brand new aspiring bloggers. Thankyou!

  17. 4 stars
    Excellent way of describing, and fastidious post to take information concerning my presentation subject matter, which i am going to convey in academy.

  18. 2 stars
    I am extremely impressed with your writing skills and also
    with the layout on your weblog. Is this a paid theme or did
    you modify it yourself? Anyway keep up the
    excellent quality writing, it’s rare to see a
    great blog like this one nowadays.

  19. 4 stars
    If some one needs expert view concerning running a blog then i propose him/her
    to visit this website, Keep up the fastidious work.

  20. 1 star
    Hi there colleagues, how is everything, and what you would like to say on the topic
    of this piece of writing, in my view its actually awesome in support of me.

  21. 3 stars
    Hi there! Do you know if they make any plugins to safeguard against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  22. 2 stars
    Hi, i read your blog from time to time and i own a similar one
    and i was just wondering if you get a lot of spam remarks?

    If so how do you prevent it, any plugin or anything you can suggest?
    I get so much lately it’s driving me insane so any help is
    very much appreciated.

  23. 1 star
    Thanks for sharing your thoughts. I really appreciate your efforts and I will be waiting for
    your further write ups thanks once again.

  24. 2 stars
    Hi there, I would like to subscribe for this webpage
    to take newest updates, therefore where can i do it please help.

  25. 2 stars
    Hello! Someone in my Facebook group shared this website with us so I came to check it
    out. I’m definitely enjoying the information. I’m book-marking and will
    be tweeting this to my followers! Fantastic blog and terrific design.

    My homepage: бесплатный банковский юрист
    [sk-bc.ru]

Reply To Vishal Swami Cancel Reply