当前位置: 代码迷 >> Android >> 在某些Android版本上创建目录
  详细解决方案

在某些Android版本上创建目录

热度:13   发布时间:2023-08-04 11:19:29.0

我在Genymotion棉花糖和HTC 10上的Nougat上测试了此代码,并且在这两个代码上都可以使用。
现在,我在Genymotion上尝试了Android 7.0,但没有创建目录。

知道为什么吗?

File file = new File(Environment
    .getExternalStorageDirectory() + File.separator +
    "SchoolAssist" + File.separator + lesson_name);

boolean isDir = file.exists();
if (!isDir)
    isDir = file.mkdirs();

if (isDir) {
    Intent notes = new Intent(getActivity(), NotesManager.class);
    notes.putExtra("dir", file.getAbsolutePath());
    startActivity(notes);
}
else
    Toast.makeText(getContext(), "Error creating directory", Toast.LENGTH_SHORT).show();

编辑:我的清单包含以下行:

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

在您的代码中,即使创建该目录也可以显示Toast。 仅在调用代码之前文件已经存在时才启动活动。

尝试这个:

File file = new File(Environment
            .getExternalStorageDirectory() + File.separator +
            "SchoolAssist" + File.separator + lesson_name);

if(!file.exists()) {
    if(file.mkdirs()) {
        startNotesManager();
    } else {
        Toast.makeText(getContext(), "Error creating directory", Toast.LENGTH_SHORT).show();
    }
} else {
    startNotesManager();
}

并实现此辅助方法以启动Activity:

private void startNotesManager() {
    Intent notes = new Intent(getActivity(), NotesManager.class);
    notes.putExtra("dir", file.getAbsolutePath());
    startActivity(notes);
}
  相关解决方案