简体   繁体   English

在内部存储中创建目录

[英]Creating directory in internal storage

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. 我正在运行CyanogenMod,并且不知道这是否会变得疯狂。

This is what I have been testing: 这是我一直在测试的:

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

And also this approac: 还有这个方法:

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. 我将逐步解释它。

Step 1 ) You should declare appropriate Manifest.xml permissions; 步骤1)您应该声明适当的Manifest.xml权限; for our case these 2 is enough. 对于我们的情况,这2个就足够了。 Also this step required both pre 6.0 and after 6.0 versions : 同样,此步骤需要6.0之前的版本和6.0以后的版本:

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

Step 2 ) In this step we will check permission for writing external storage then will do whatever we want. 步骤2)在这一步中,我们将检查对写入外部存储的权限,然后执行我们想要的任何操作。

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;
    }

}

Step 3 ) Handling permission rationale and showing dialog, please read comments for info 步骤3)处理权限原理并显示对话框,请阅读注释以获取信息

/**
 * 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();
}

Step 4 ) Getting permission result in Activity : 步骤4)在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);
    }
}

Step 5 ) In case of using internal storage. 步骤5)如果使用内部存储器。 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 您可以阅读此页面以获取有关运行时权限的信息: 运行时权限请求

My advice : You can create an Activity which responsible of this permissions like BasePermissionActivity and declare methods @Step 3 in it. 我的建议:您可以创建一个负责该权限的Activity ,例如BasePermissionActivity,并在其中声明方法@Step 3。 Then you can extend it and call your request permission where you want. 然后,您可以扩展它,并在需要的地方调用您的请求权限。

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 我也搜索了一下,发现了@Step 3代码的Github链接,以备您检查: yalantis / ucrop / sample / BaseActivity.java

You forgot to add the "/" before adding the file name so your path is compiled like this: 您忘记添加文件名之前添加了“ /”,因此路径的编译如下:

/data/data/com.myPackageNametheFolder /data/data/com.myPackageNametheFolder

File folder = new File(getFilesDir() + "/" + "theFolder");

OR 要么

File folder = new File(getFilesDir(),"theFolder");

You'll get this instead 你会得到这个

/data/data/com.myPackageName/theFolder /data/data/com.myPackageName/theFolder

PS : There is no dumb phone all phones are Smart Phones 'Bad dum tss' PS:没有哑手机,所有手机都是智能手机“ Bad dum tss”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM