当Min SDK为L时,在Android M上请求权限

Asf*_*sfK 4 android android-5.1.1-lollipop android-6.0-marshmallow

我正在编写应该在Android L和M上运行的应用程序

您可能知道,对于Android M,需要在代码中询问写入\从外部存储(sdcard)读取的权限,如下所示:

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

但是,我遇到了一个问题,因为调用checkSelfPermission需要API级别23(而不是22,因为我需要Lollipop支持).

我试图添加,@TargetApi(Build.VERSION_CODES.MNC)但我面临另一个问题 -"Cannot resolved symbol MNC"

那么问题是,我如何编写代码来保存sdcard中的文件,Lollipop和Marshmallow?

编辑:项目结构设置:

编译Sdk版本:API 23:Android 5.X(MNC

Min Sdk版本:API 22:Android 5.1(Lollipop)

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

谢谢

Rib*_*das 7

将编译版本更改为API 23(MARSHMALLOW)并添加依赖项

dependencies {
  ...
 compile 'com.android.support:appcompat-v7:23.1.1'
  ...
  }
Run Code Online (Sandbox Code Playgroud)

并为只有棉花糖的条件

  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;
                        }
                    }
Run Code Online (Sandbox Code Playgroud)

这是因为checkselfpermission方法只适用于marsmallow