0

我认为我的智能手机是一个哑机。试图创建一个文件夹,它似乎只是不会被创建。我正在运行 CyanogenMod,但不知道这是否让它变得疯狂。

这是我一直在测试的:

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

还有这个方法:

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

2 回答 2

3

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

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

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

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

}

步骤 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();
}

步骤 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);
    }
}

步骤 5 )在使用内部存储的情况下。您无需检查运行时权限即可使用内部存储。

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

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

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

我也搜索了一下,发现代码的 Github 链接@Step 3 如果你想检查:yalantis/ucrop/sample/BaseActivity.java

于 2016-02-18T01:20:59.477 回答
1

您在添加文件名之前忘记添加“/”,因此您的路径编译如下:

/data/data/com.myPackageNametheFolder

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

或者

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

你会得到这个

/data/data/com.myPackageName/theFolder

PS:没有哑手机,所有手机都是智能手机'Bad dum tss'

于 2016-02-17T23:29:56.497 回答