Android之文件管理_SDcard基本操作
程序员文章站
2022-05-16 21:01:05
...
做软件的时候 也许要存数据要用到SD卡 所以在用之前 最好检测下 SD卡是否可用
详解地址传送门 http://www.runoob.com/w3cnote/android-tutorial-file.html
Android判断SD卡是否可用,可按以下方式:
首先要在AndroidManifest.xml中增加SD卡访问权限
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.判断SD卡是否存在
private boolean ExistSDCard() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return true;
} else
return false;
}
官网代码
//判断是否可写
/* 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;
}
Android中判断SD卡状态
String status = Environment.getExternalStorageState();
if (status.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
Toast.makeText(TechoLite.this, "SD卡存在", Toast.LENGTH_LONG).show();
// 此时SD是可读写的
} else if (status.equalsIgnoreCase(Environment.MEDIA_MOUNTED_READ_ONLY)) {
Toast.makeText(TechoLite.this, "虽然SD存在,但是为只读状态", Toast.LENGTH_LONG).show();
} else if (status.equalsIgnoreCase(Environment.MEDIA_REMOVED)) {
Toast.makeText(TechoLite.this, "SD不存在", Toast.LENGTH_LONG).show();
} else if (status.equalsIgnoreCase(Environment.MEDIA_SHARED)) {
Toast.makeText(TechoLite.this, "虽然SD卡存在,但是正与PC等相连接", Toast.LENGTH_LONG).show();
} else if (status.equalsIgnoreCase(Environment.MEDIA_BAD_REMOVAL)) {
Toast.makeText(TechoLite.this, "SD卡在挂载状态下被错误取出", Toast.LENGTH_LONG).show();
} else if (status.equalsIgnoreCase(Environment.MEDIA_CHECKING)) {
Toast.makeText(TechoLite.this, "正在检查SD卡", Toast.LENGTH_LONG).show();
} else if (status.equalsIgnoreCase(Environment.MEDIA_NOFS)) {
Toast.makeText(TechoLite.this, "虽然SD卡存在,但其文件系统不被支持", Toast.LENGTH_LONG).show();
} else if (status.equalsIgnoreCase(Environment.MEDIA_UNMOUNTABLE)) {
Toast.makeText(TechoLite.this, "虽然SD卡存在,但是无法被挂载", Toast.LENGTH_LONG).show();
} else if (status.equalsIgnoreCase(Environment.MEDIA_UNMOUNTED)) {
Toast.makeText(TechoLite.this, "虽然SD卡存在,但是未被挂载", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(TechoLite.this, "其他原因", Toast.LENGTH_LONG).show();
}