android数据存储之外部存储(External Storage)
Android设备支持外部存储器,可以是可移动存储器(如SD卡),也可以是内置在设备中的外部存储器(不可移动)。
如果希望外部存储器上的文件只对本程序有用,并且当程序被卸载时目录中的文件自动被系统删除,可以使用如下目录
/Android/data/<package_name>/
核心代码:
/**
* 得到缓存的目录(apk卸载时系统自动删除该packagename目录)
* @param context
* @return
*/
public static File getCacheDirectory(Context context) {
File appCacheDir = null;
if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
appCacheDir = getExternalCacheDir(context);
}
if (appCacheDir == null) {
//返回 /data/data/<package_name>/
appCacheDir = context.getCacheDir();
}
if (appCacheDir == null) {
L.w("Can't define system cache directory! The app should be re-installed.");
}
return appCacheDir;
}
/**
* 返回/Android/data/<package_name>/file,若file目录不存在则创建
* @param context
* @return
*/
private static File getExternalCacheDir(Context context) {
File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
File appCacheDir = new File(new File(dataDir, context.getPackageName()), "file");
if (!appCacheDir.exists()) {
if (!appCacheDir.mkdirs()) {
L.w("Unable to create external cache directory");
return null;
}
try {
new File(appCacheDir, ".nomedia").createNewFile();
} catch (IOException e) {
L.i("Can't create \".nomedia\" file in application external cache directory");
}
}
return appCacheDir;
}
/**
* 权限判断
* @param context
* @return
*/
private static boolean hasExternalStoragePermission(Context context) {
int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
return perm == PackageManager.PERMISSION_GRANTED;
}