我有一个使用外部存储来存储照片的应用程序。根据需要,在 list 中要求以下权限

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

并使用以下内容检索所需的目录
File sdDir = Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd", Locale.US);
String date = dateFormat.format(new Date());
storageDir = new File(sdDir, getResources().getString(
            R.string.storagedir)
            + "-" + date);

// Create directory, error handling
if (!storageDir.exists() && !storageDir.mkdirs()) {
 ... fails here

该应用程序可以在Android 5.1到2.3上正常运行;它已经在Google Play上使用了一年多。

将我的一部测试手机(Android One)升级到6后,尝试创建必要目录“/sdcard/Pictures/myapp-yy-mm”时,现在返回错误。

sd卡被配置为“便携式存储”。我已经格式化了SD卡。我已经更换了。我已经重启了。一切都无济于事。

另外,内置的android屏幕截图功能(通过Power + Lower降低音量)“由于存储空间有限,或者应用程序或您的组织不允许使用”而失败。

有任何想法吗?

最佳答案

我遇到了同样的问题。 Android中有两种类型的权限:

  • 危险(访问联系人,写入外部存储...)
  • 普通

  • 普通权限由Android自动批准,而危险权限需要由Android用户批准。

    这是在Android 6.0中获取危险权限的策略
  • 检查您是否已授予
  • 权限
  • 如果您的应用已被授予许可,请继续并正常执行。
  • 如果您的应用尚未获得许可,请要求用户批准
  • 在onRequestPermissionsResult上听取用户批准

  • 这是我的情况:我需要写外部存储。

    首先,请检查我是否具有以下权限:
    ...
    private static final int REQUEST_WRITE_STORAGE = 112;
    ...
    boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        ActivityCompat.requestPermissions(parentActivity,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_WRITE_STORAGE);
    }
    

    然后检查用户的批准:
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode)
        {
            case REQUEST_WRITE_STORAGE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    //reload my activity with permission granted or use the features what required the permission
                } else
                {
                    Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
                }
            }
        }
    
    }
    

    您可以在此处阅读有关新权限模型的更多信息:https://developer.android.com/training/permissions/requesting.html

    关于android - Android 6.0棉花糖。无法写入SD卡,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33139754/

    10-12 00:26
    查看更多