仅在Android 6.0中没有此类文件或目录 [英] No such file or Directory only in Android 6.0

查看:118
本文介绍了仅在Android 6.0中没有此类文件或目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码在Marshmallow之前的设备上运行正常,但在Marshmallow上不能正常工作.

Below code is working fine on pre-Marshmallow devices but not in Marshmallow.

这些是清单中的权限

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

这是代码

public void saveImageToSDCard(Bitmap bitmap) {
    File myDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            pref.getGalleryName());

    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Wallpaper-" + n + ".jpg";
    File file = new File(myDir, fname);
    if (file.exists())
        file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
        Uri uri = getImageContentUri(_context,file);

        Log.d(TAG, "Wallpaper saved to: " + file.getAbsolutePath());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

当我手动允许存储权限时,相同的代码也可以工作

这是Nitesh Pareek给出的解决方案.

Here is the solution given by Nitesh Pareek.

private boolean hasPermissions(Context context, String[] permissions) {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}
String[] PERMISSIONS = new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE};

    if (!hasPermissions(this, PERMISSIONS)) {
        ActivityCompat.requestPermissions(this, PERMISSIONS, 11);
        return;
    }

推荐答案

从Android 6.0(API级别23)开始,用户在应用程序运行时(而不是在安装应用程序时)授予应用程序权限.

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.

这就是为什么它可以在lolipop之前的版本中使用,并且不能在API 23上使用的原因.仅Android Manifest中的权限还很不足,您还需要在运行时添加它们.有关更多详细信息,请参考此处.

This is why it works in pre-lolipop versions, and doesn't on API 23. Permissions in Android Manifest alone are not enough, you need to add them at runtime as well. Refer here for more details.

这篇关于仅在Android 6.0中没有此类文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆