手机系统内部空间
Context.getFilesDir().getPath(); // /data/data/<PackageName>/files
Context.getCacheDir().getPath(); // /data/data/<PackageName>/cache
Environment.getDataDirectory().getPath(); // /data
Environment.getDownloadCacheDirectory().getPath(); // /cache
Environment.getRootDirectory().getPath(); // /system
上述这些便是访问所有手机系统内部空间的方法,可以发现Context提供的方法总是指向App的私有路径的即我们的App数据写入这个路径并不用权限,而高版本的API即使有权限也不能写入上述Environment方法对应的路径。不过一般不会将数据写入系统内部空间
手机内部空间
俗称内部sd卡,即App一般会将数据写入其中。
Context.getExternalCacheDir().getPath(); // /storage/emulated/0/Android/data/<PackageName>/cache
Context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath(); // /storage/emulated/0/Android/data/<PackageName>/files/Download
Context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath(); // /storage/emulated/0/Android/data/<PackageName>/files/Pictures
Environment.getExternalStorageDirectory().getPath(); // /storage/emulated/0(内部空间根目录)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath(); // /storage/emulated/0/Download
这些是所有访问手机内部空间的方法,同样的Context提供的方法总是指向App的私有路径的即我们的App数据写入这个路径并不用权限,而要访问Environment所对应的路径则给App加上相关权限即可。 注意上述Environment.DIRECTORY_PICTURES与Environment.DIRECTORY_DOWNLOADS无非就是添加一个目录, 前者为Pictures,后者为Download。
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
这个用于判断内部空间是否挂载。
外部SD卡空间
这里提供一个方法摘自网络,用的反射所以兼容性很强,避免定制Rom带来的影响
public static String getStoragePath(Context mContext, boolean is_removale) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = null;
try {
result = getVolumeList.invoke(mStorageManager);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (is_removale == removable) {
return path;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
这里is_removale参数一般传递为true 表示有外置sd卡,如果没有直接使用Api提供的方法即可。最后的path即为外置sd卡根目录文件夹File。
File.getFreeSpace();
File.getUsableSpace();
这两个方法均可访问文件所在磁盘下剩余的空间,与file文件无关。
File.getTotalSpace();
这个方法则是磁盘总空间。
所以我们判断外置sd卡是否挂载可用:
File file=new File(path);
if(file.getTotalSpace()==0){
//外置sd卡未挂载
}
path为上述方法所返回的外置sd卡路径。