Android读取手机卡
- 格式:docx
- 大小:14.95 KB
- 文档页数:2
使用 Environment.getExternalStorageDirectory().getPath() 替代sdcard路径
以前的Android(4.1之前的版本)中,SDcard跟路径通过“/sdcard”或者“/mnt/sdcard”来表示,而在Jelly Bean系统中修改为了“/storage/sdcard0”,以后可能还会有多个SDcard的情况。目前为了保持和之前代码的兼容,sdcard路径做了link映射。
为了使您的代码更加健壮并且能够兼容以后的Android版本和新的设备,请通过Environment.getExternalStorageDirectory().getPath()来获取sdcard路径,如果您需要往sdcard中保存特定类型的内容,可以考虑使用Environment.getExternalStoragePublicDirectory(String
type)函数,该函数可以返回特定类型的目录,目前支持如下类型:
DIRECTORY_ALARMS //警报的铃声
DIRECTORY_DCIM //相机拍摄的图片和视频保存的位置
DIRECTORY_DOWNLOADS //下载文件保存的位置
DIRECTORY_MOVIES //电影保存的位置, 比如 通过google play下载的电影
DIRECTORY_MUSIC //音乐保存的位置
DIRECTORY_NOTIFICATIONS //通知音保存的位置
DIRECTORY_PICTURES //下载的图片保存的位置
DIRECTORY_PODCASTS //用于保存podcast(博客)的音频文件
DIRECTORY_RINGTONES //保存铃声的位置
Getting access to external storage
In order to read or write files on the external storage, your app must acquire
the READ_EXTERNAL_STORAGE orWRITE_EXTERNAL_STORAGE system permissions. For example:
...
Saving files that are app-private
Beginning with Android 4.4, reading or writing files in your app's private directories does not
require theREAD_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permissions. So you can
declare the permission should be requested only on the lower versions of Android by adding
the maxSdkVersion attribute:
Checking media availability
/* 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;
}
Saving files that can be shared with other apps
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}