1、概述
app在开发的时候经常会遇到要存储一些文本,图片,或者是网络获取回来的更新包。这个时候就需要开辟它的存储区域
2、存储介绍
官方提供的存储位置说明:http://developer.android.com/guide/topics/data/data-storage.html
Android 的5中存储方式:
Internal Storage (内部存储)
External Storage (外部存储 如sd 卡)
权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
SQLite Databases (数据库)
Network Connection (网络)
Shared Preferences (键值对,轻量级文件存储)
SharedPreference 简单操作访问:
//默认SharePreference
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mEditor = mPreferences.edit(); // edit 编辑完 commit 结束
mEditor.putString(prefix + mImageName, mImageDateString);// 更新时间
mEditor.commit();
//指定SharePreference
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); // Commit the edits! editor.commit();
SharedPreferences mySharedPreferences= getSharedPreferences("test", Activity.MODE_PRIVATE);
Ps: 注意下每次put的时候都要重新拿下edit()然后commit() 以下代码是错误的,不是同一个edit
错误的:
正确的:
3、存储位置
这里着重介绍几种:
a) 存储在app的私有目录下,及在/data/data/包名下 (要root了才能看到)
dir = mContext.getDir("dir_name", Context.MODE_PRIVATE);
b) 存储在sd卡公用目录 (如果卸载该app 无法卸载该文件夹)
//普通的外部存储器(应该先判断是否拥有外部存储器 External storage)
String pathString = Environment.getExternalStorageDirectory() + "/" +filename;
公有目录:
Environment.getExternalStoragePublicDirectory
c) 存储在sd卡的私有目录,及在sdk卡开辟一个/Android/data/包名 (如果卸载该app 自动卸载该文件夹)
//使用app 在sd卡上的私有目录 (应该先判断是否拥有外部存储器 External storage)
String pathString = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/" +filename;
d) 判断是否存在外部 External storage
摘自官网
/* Checks if external storage is available for read and write */ public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } /* Checks if external storage is available to at least read */ public boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; }
ps:app中get到的路径列表
mContext.getDir("demoDir", Context.MODE_PRIVATE)
= /data/data/com.myapp_package/app_demoDir
mContext.getCacheDir()
= /data/data/com.myapp_package/cache
mContext.getFilesDir()
= /data/data/com.myapp_package/files
mContext.getObbDir()
= /storage/emulated/0/Android/obb/com.myapp_package
mContext.getExternalCacheDir()
= /storage/emulated/0/Android/data/com.myapp_package/cache
mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
= /storage/emulated/0/Android/data/com.myapp_package/files/Download
Environment.getRootDirectory()
= /system
Environment.getDataDirectory()
= /data
Environment.getExternalStorageDirectory()
= /storage/emulated/0