Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asking permission on Android M when Min SDK is L

I'm writing app that should run on Android L and M.

As you probably know, for Android M need to ask permission in the code for write\read from external storage (sdcard), like this:

if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==
        PackageManager.PERMISSION_GRANTED)
    requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);

but, I faced a problem because call checkSelfPermission requires API level 23 (and not 22, as I need for Lollipop support).

I tried to add @TargetApi(Build.VERSION_CODES.MNC) but I faced with another issue - "Cannot resolved symbol MNC"

So the question, how can I write code to save file in the sdcard, for Lollipop and Marshmallow?

EDIT: Project Structure settings:

Compile Sdk Version: API 23:Android 5.X(MNC

Min Sdk Version: API 22:Android 5.1 (Lollipop)

Target Sdk Version: API 23:Android 5.X(MNC)

Thank you

like image 574
AsfK Avatar asked Feb 09 '23 13:02

AsfK


1 Answers

Change the compile version to API 23(MARSHMALLOW) and add dependecies

dependencies {
  ...
 compile 'com.android.support:appcompat-v7:23.1.1'
  ...
  }

and put a condition for only marshmallow

  if (Build.VERSION.SDK_INT > 22) {
                        if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==
    PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider calling
                            //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for Activity#requestPermissions for more details.
                            return;
                        }
                    }

this is because the checkselfpermission method only work in marsmallow

like image 64
Ribin Haridas Avatar answered Mar 07 '23 00:03

Ribin Haridas