在内部存储中创建目录 [英] Creating directory in internal storage

查看:101
本文介绍了在内部存储中创建目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我的智能手机是静音电话. 试图创建一个文件夹,似乎它不会被创建. 我正在运行CyanogenMod,不知道这是否会解决问题.

I think that my smartphone is a dumbphone. Trying to create a folder and it seems that it just wont get created. I am running CyanogenMod and dont know if this make it goes nuts.

这是我一直在测试的:

File folder = new File(getFilesDir() + "theFolder");
if(!folder.exists()){
folder.mkdir();
}

还有这个方法:

File folder = getDir("theFolder",Context.MODE_PRIVATE);

推荐答案

这个答案很旧,我对此进行了更新.我包括内部和外部存储.我将逐步解释它.

This answer was old and I updated it. I included internal and external storage. I will explain it step by step.

步骤1);您应声明适当的Manifest.xml权限;对于我们的情况,这2个就足够了.同样,此步骤需要6.0之前的版本和6.0以后的版本:

Step 1 ) You should declare appropriate Manifest.xml permissions; for our case these 2 is enough. Also this step required both pre 6.0 and after 6.0 versions :

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

第2步).在这一步中,我们将检查写入外部存储的权限,然后执行我们想做的所有事情.

Step 2 ) In this step we will check permission for writing external storage then will do whatever we want.

public static int STORAGE_WRITE_PERMISSION_BITMAP_SHARE =0x1;

public Uri saveBitmapToFileForShare(File file,Uri uri){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
    && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

//in this side of if we don't have permission 
//so we can't do anything. just returning null and waiting user action

    requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
   "permission required for writing external storage bla bla ..."
                REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);
        return null;
    }else{
        //we have right about using external storage. do whatever u want.
        Uri returnUri=null;
        try{
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver() ,uri);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            returnUri=Uri.fromFile(file);
        }
        catch (IOException e){
            //can handle for io exceptions
        }

        return returnUri;
    }

}

第3步):处理权限原理并显示对话框,请阅读注释以获取信息

Step 3 ) Handling permission rationale and showing dialog, please read comments for info

/**
 * Requests given permission.
 * If the permission has been denied previously, a Dialog will prompt the user to grant the
 * permission, otherwise it is requested directly.
 */
protected void requestPermission(final String permission, String rationale, final int requestCode) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
        showAlertDialog("Permission required", rationale,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(BasePermissionActivity.this,
                                new String[]{permission}, requestCode);
                    }
                }, getString(android.R.string.ok), null, getString(android.R.string.cancel));
    } else {
        ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
    }
}

/**
 * This method shows dialog with given title & content.
 * Also there is an option to pass onClickListener for positive & negative button.
 *
 * @param title                         - dialog title
 * @param message                       - dialog content
 * @param onPositiveButtonClickListener - listener for positive button
 * @param positiveText                  - positive button text
 * @param onNegativeButtonClickListener - listener for negative button
 * @param negativeText                  - negative button text
 */
protected void showAlertDialog(@Nullable String title, @Nullable String message,
                               @Nullable DialogInterface.OnClickListener onPositiveButtonClickListener,
                               @NonNull String positiveText,
                               @Nullable DialogInterface.OnClickListener onNegativeButtonClickListener,
                               @NonNull String negativeText) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.setPositiveButton(positiveText, onPositiveButtonClickListener);
    builder.setNegativeButton(negativeText, onNegativeButtonClickListener);
    mAlertDialog = builder.show();
}

第4步):在活动"中获取许可权结果:

Step 4 ) Getting permission result in Activity :

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case STORAGE_WRITE_PERMISSION_BITMAP_SHARE:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                shareImage();
            }else if(grantResults[0]==PackageManager.PERMISSION_DENIED){
                //this toast is calling when user press cancel. You can also use this logic on alertdialog's cancel listener too.
                Toast.makeText(getApplicationContext(),"you denied permission but you need to give permission for sharing image. "),Toast.LENGTH_SHORT).show();
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

第5步)(如果使用内部存储).您无需检查运行时权限即可使用内部存储.

Step 5 ) In case of using internal storage. You don't need to check runtime permissions for using internal storage.

//this creates a png file in internal folder
//the directory is like : ......data/sketches/my_sketch_437657436.png
File mFileTemp = new File(getFilesDir() + File.separator
                + "sketches"
                , "my_sketch_"
                + System.currentTimeMillis() + ".png");
        mFileTemp.getParentFile().mkdirs();

您可以阅读此页面以获取有关运行时权限的信息:运行时权限请求

You can read this page for information about runtime permissions : runtime permission requesting

我的建议:您可以创建一个负责此权限的Activity,例如BasePermissionActivity,并在其中声明方法@Step 3.然后,您可以扩展它,并在需要的地方调用您的请求权限.

My advice : You can create an Activity which responsible of this permissions like BasePermissionActivity and declare methods @Step 3 in it. Then you can extend it and call your request permission where you want.

我也进行了一些搜索,发现了@Step 3代码的Github链接,以备您检查:

Also I searched a bit and found the Github link of codes @Step 3 in case of you want to check : yalantis/ucrop/sample/BaseActivity.java

这篇关于在内部存储中创建目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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