gpt4 book ai didi

android - Android 内部/外部存储上的私有(private)文件夹

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:36:28 25 4
gpt4 key购买 nike

我想为我的应用程序数据创建一个私有(private)文件夹。从设备中删除应用程序时,必须自动删除此文件夹。根据http://developer.android.com/training/basics/data-storage/files.html ,我必须创建一个私有(private)文件夹。我怎样才能做到这一点。我的代码如下。删除应用程序时不会删除文件夹。

 public static String getAppFilePath(Context context) {

String path = "";
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
path = Environment.getExternalStorageDirectory()
.getAbsolutePath();

path += "/myFolder";

} else {

ContextWrapper c = new ContextWrapper(context);
path = c.getFilesDir().getPath();
}
File ret = new File(path);
if (!ret.exists()) {
ret.mkdirs();
}
return path;
}

最佳答案

你做错了。

根据您指出的文档:

If you want to save files that are private to your app, you can acquire the appropriate directory by calling getExternalFilesDir() and passing it a name indicating the type of directory you'd like. Each directory created this way is added to a parent directory that encapsulates all your app's external storage files, which the system deletes when the user uninstalls your app.

For example, here's a method you can use to create a directory for an individual photo album:

public File getAlbumStorageDir(Context context, String albumName) {
// Get the directory for the app's private pictures directory.
File file = new File(context.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}

If none of the pre-defined sub-directory names suit your files, you can instead call getExternalFilesDir() and pass null. This returns the root directory for your app's private directory on the external storage.

Remember that getExternalFilesDir() creates a directory inside a directory that is deleted when the user uninstalls your app. If the files you're saving should remain available after the user uninstalls your app—such as when your app is a camera and the user will want to keep the photos—you should instead use getExternalStoragePublicDirectory().

所以基本上您需要在上面的示例中使用 getExternalFilesDir 函数来在卸载应用程序时将其删除。


根据 getExternalFilesDir() 的文档

Parameters

type The type of files directory to return. May be null for the root of the files directory or one of the following constants for a subdirectory: DIRECTORY_MUSIC, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES, DIRECTORY_ALARMS, DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES, or DIRECTORY_MOVIES.

因此,除了预定义类型之外,您还可以使用 null 作为目录的根目录。

关于android - Android 内部/外部存储上的私有(private)文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33232321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com