棉花糖存储和图库使用的读写权限

Read and Write permission for storage and gallery usage for marshmallow

我正在开发一个 android 应用程序,其中需要提供读取和写入外部存储的权限。我的要求是 select 来自图库的图片并在我的应用中使用它。除 Marshmallow 设备外,一切正常。我想为 Marshmallow 提供权限。谁能帮我解决这个问题?

可以实现如下...

public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{

  private static final int REQUEST_WRITE_PERMISSION = 786;

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {            
        openFilePicker();
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    requestPermission();
  }

  private void requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
    } else {
        openFilePicker();
    }
  }
}

通读 Runtime permissions - Android M and its reference project

权限流程已更改,要求在运行时询问权限,最好是在需要时询问。同样.. 权限也被归类为 Normal and Dangerous 这也将导致权限组。

另外,如果你想请求多个权限。你可以做到这一点。

private ArrayList<String> permisos;

private void someMethod()
{
      ..

      verificarPermisos(Manifest.permission.READ_EXTERNAL_STORAGE );
      verificarPermisos(Manifest.permission.ACCESS_FINE_LOCATION );
      verificarPermisos(Manifest.permission.ACCESS_COARSE_LOCATION );
      if (permisos.size()!=0)
      {
         solicitarPermisos(permisos.toArray(new String[permisos.size()]));
      }

      ..

 }


@TargetApi(23)
void verificarPermisos(String permiso){
    if (ContextCompat.checkSelfPermission(this,permiso)
            != PackageManager.PERMISSION_GRANTED) {
        permisos.add(permiso);
        // Should we show an explanation?
        if (shouldShowRequestPermissionRationale(permiso)) {

        }

    }
}

@TargetApi(23)
void solicitarPermisos(String[] permiso){

    requestPermissions(permiso, 1);

}

首先,我使用“verificarPermisos()”方法检查权限是否已被授予。如果它们未被授予,我将它们添加到“permisos”arraylist。最后,未授予的权限被请求以 String[] 数组格式传递。

请注意,您只能在 MashMellow(API 23) 或更高版本之后请求权限。因此,如果您的应用程序还针对 MashMellow 之前的 android 版本,您可以使用“@TargetApi()”注释,并且只有在目标为 API 23 或更高。
希望有所帮助,问候。

检查每一种情况

if denied - showing Alert dialog to user why we need permission

public static final int STORAGE_PERMISSION_REQUEST_CODE= 1;


    private void askPermissions() {

    int permissionCheckStorage = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE); 

   // we already asked for permisson & Permission granted, call camera intent
    if (permissionCheckStorage == PackageManager.PERMISSION_GRANTED) {

        //do what you want

    } else {

           // if storage request is denied
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("You need to give permission to access storage in order to work this feature.");
            builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            builder.setPositiveButton("GIVE PERMISSION", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();

                    // Show permission request popup
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            STORAGE_PERMISSION_REQUEST_CODE);
                }
            });
            builder.show();

        } //asking permission for first time 
          else {
             // Show permission request popup for the first time
                        ActivityCompat.requestPermissions(AddWorkImageActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                STORAGE_PERMISSION_REQUEST_CODE);

                    }

    }
}

检查权限结果

 @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case STORAGE_PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // check whether storage permission granted or not.
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //do what you want;
                }
            }
            break;
        default:
            break;
    }
}

you can just copy and paste this code, it works fine. change context(this) & permissions according to you.

为了在存储中写入文件, 首先需要在manifest.xml,

中添加写权限

那么, 在 Android 6 中,它包含针对某些任务的权限系统。每个应用程序都可以在运行时请求所需的权限。因此,让我们打开 Activity class 添加以下代码以请求运行时权限。

使用

检查您的应用程序是否具有运行时写入权限
override fun onRequestPermissionsResult(requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray) {

    when(requestCode)  {

        100 -> {
            if (grantResults.size > 0 && permissions[0] == Manifest.permission.WRITE_EXTERNAL_STORAGE) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                
                }
            }

        }
    }

}

检查AndroidManifest.xml!!

    <?xml version="1.0" encoding="utf-8"?>
<manifest 
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.yoganetwork">
<!-- Internet Permission -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission 
android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission 
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.YogaNetwork">
    <activity android:name=".LoginActivity"></activity>
    <activity android:name=".DashboardActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" 
/>

            <category 
android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".RegisterActivity" />
    <activity android:name=".MainActivity" />
</application>

</manifest>