您的位置:首页 > 移动开发 > Android开发

Android 使用SD卡的检查

2013-12-12 17:13 253 查看
1、检查是否存在SD卡

/**
* 检查是否存在SD卡
* @return
*/
public static boolean isSdcardExist(){
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ? true : false;
}


2、检查是否有SD卡存储与读取权限

/**
* 返回SD卡是否由读写权限
* @param requireWriteAccess 是否需要写权限
* @return
*/
public static boolean hasStorage(boolean requireWriteAccess){
if (isSdcardExist()) {
if(requireWriteAccess){
return checkFSWritable();
}else{
return true;
}
}
return false;
}


/**
* 检查是否可以读写
* @return
*/
private static boolean checkFSWritable() {
String dirName = Constants.APP_DIR;
File dir = new File(dirName);
if(!dir.isDirectory() && !dir.mkdirs()) return false;
return dir.canWrite();
}


3、检查SD卡控件是否充足

/**
* 得到SD卡空余空间大小
* @return
*/
private static long getAvailableStorage(){
if(!hasStorage(true)){
return Constants.NO_STORAGE_ERROR;
}else{
StatFs stat = new StatFs(Constants.EXTERNAL_STORAGE_DIR);
return (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
}
}


4、得到SD卡状态信息

/**
* 得到SD卡读取状态编码
* 如果没有可用空间  返回没有SD卡
* 如果空间小于一定值  返回SD卡空间不足
* 如果空间充足  返回OK
* @return
*/
private static int getStorageStatus(){
long remaining = getAvailableStorage();
if(remaining == Constants.NO_STORAGE_ERROR){
return Constants.STORAGE_STATUS_NONE;
}
return remaining < Constants.LOW_STORAGE_THRESHOLD ? Constants.STORAGE_STATUS_LOW : Constants.STORAGE_STATUS_OK;
}


5、检查是否存在相应目录,如果没有则建立

/**
* 查询APP目录是否存在并建立不存在的目录
* @return
*/
static int checkAppDirsAndMkdirs(){
int status = getStorageStatus();
if(status == Constants.STORAGE_STATUS_NONE){
return Constants.STORAGE_STATUS_NONE;
}else if(status == Constants.LOW_STORAGE_THRESHOLD){
return Constants.STORAGE_STATUS_LOW;
}else{
String[] appDirs = new String[]{
Constants.APP_DIR, Constants.ERROR_LOG_DIR
};

File file = null;
for (String dir : appDirs) {
file = new File(dir);
if (!file.exists() || !file.isDirectory()) {
file.mkdirs();
}
}
return Constants.STORAGE_STATUS_OK;
}
}


6、复制文件或存储文件流

如果是文件流需要修改部分代码

private boolean copyAPPToSD(String strOutFileName,String str)
{
InputStream myInput = null;
OutputStream myOutput = null;
try {
File target = new File(str);
if(StorageCheck.checkAppDirsAndMkdirs()==Constants.STORAGE_STATUS_OK
&&!target.exists()){
target.createNewFile();
}
myOutput = new FileOutputStream(strOutFileName);
myInput = context.getAssets().open(str);
byte[] buffer = new byte[1024];
int length = myInput.read(buffer);
while(length > 0)
{
myOutput.write(buffer, 0, length);
length = myInput.read(buffer);
}
myOutput.flush();
myInput.close();
myOutput.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
Log.e("出现错误1:",e1.getMessage());
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("出现错误2:",e.getMessage());
return false;
}
return true;
}


如果只是纯粹检查SD卡的话就调用 4或5 就行了(其他方法要加上方便调用哦)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android SD卡 存储卡