Android:使用API​​ 25创建文件夹(7.1.2)

时间:2017-05-05 10:03:33

标签: android permissions

请帮帮我! 我的设备刚刚更新到Android 7.1.2,然后我的应用无法首次创建文件夹。(该代码适用于所有以前的Android版本,包括7.1.1)。

我尝试了什么:

  • 将android.permission.WRITE_EXTERNAL_STORAGE添加到清单文件中

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
  • 检查onCreate()

    的运行时权限
    private static final int REQUEST_CODE_PERMISSION = 1;
    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermission = {
                                Manifest.permission.READ_EXTERNAL_STORAGE, 
                                Manifest.permission.WRITE_EXTERNAL_STORAGE};
            grantPermissions(mPermission);
        } else createFolder("/MyFolder/");
    }
    
    private void grantPermissions(String[] mPermission) {
        if (ActivityCompat.checkSelfPermission(this, mPermission[0])
            != PackageManager.PERMISSION_GRANTED ||
            ActivityCompat.checkSelfPermission(this, mPermission[1])
            != PackageManager.PERMISSION_GRANTED) {
    
            ActivityCompat.requestPermissions(this, mPermission,REQUEST_CODE_PERMISSION);
        } else createFolder("/MyFolder/");
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION: {
                if (grantResults.length > 0) {
                    if (grantResults.length == 2 &&
                        grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                        grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                        createFolder("/MyFolder/");
                    } else  {Toast.makeText(this, "The app was not allowed to granted some Permissions. So that it cannot function properly. Please consider granting it these permissions", Toast.LENGTH_LONG).show();}
                } else  {}
            }
        }
    }
    
  • 创建文件夹功能

    public static void createFolder(String folder) {
        File root = Environment.getExternalStorageDirectory();
        String path = root.getAbsolutePath() + folder;
        File fileFolder = new File(path);
        if (!fileFolder.exists()) 
            Log.e("Utilities","create "+folder+" : "+fileFolder.mkdirs());
    }
    

    使用7.1.2,第一次运行应用程序时,fileFolder.mkdirs()始终返回false。重启应用程序,它返回true!有帮助吗?非常感谢!

0 个答案:

没有答案