如何判断sdcard是否安装在Android中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/902089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to tell if the sdcard is mounted in Android?
提问by KFB
I'm working on an Android application that needs to look at what images a user has stored. The problem is that if the user has the sdcard mounted via the USB cable, I can't read the list of images on the disk.
我正在开发一个需要查看用户存储的图像的 Android 应用程序。问题是,如果用户通过 USB 电缆安装了 sdcard,我无法读取磁盘上的图像列表。
Does anyone know of a way to tell if the usb is mounted so that I could just pop up a message informing the user that it won't work?
有没有人知道一种方法来判断 USB 是否已安装,以便我可以弹出一条消息通知用户它无法工作?
回答by jargonjustin
If you're trying to access images on the device, the best method is to use the MediaStore content provider. Accessing it as a content providerwill allow you to query the images that are present, and map content://
URLs to filepaths on the device where appropriate.
如果您尝试访问设备上的图像,最好的方法是使用MediaStore 内容提供程序。将其作为内容提供者访问将允许您查询存在的图像,并content://
在适当的情况下将URL映射到设备上的文件路径。
If you still need to access the SD card, the Camera application includes an ImageUtilsclass that checks if the SD card is mounted as follows:
如果您仍然需要访问 SD 卡,Camera 应用程序包含一个ImageUtils类,用于检查 SD 卡是否已安装,如下所示:
static public boolean hasStorage(boolean requireWriteAccess) {
//TODO: After fix the bug, add "if (VERBOSE)" before logging errors.
String state = Environment.getExternalStorageState();
Log.v(TAG, "storage state is " + state);
if (Environment.MEDIA_MOUNTED.equals(state)) {
if (requireWriteAccess) {
boolean writable = checkFsWritable();
Log.v(TAG, "storage writable is " + writable);
return writable;
} else {
return true;
}
} else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
回答by kakopappa
Here is the checkFsWritable missing function in jargonjustin
post
这是jargonjustin
post 中的 checkFsWritable 缺失函数
private static boolean checkFsWritable() {
// Create a temporary file to see whether a volume is really writeable.
// It's important not to put it in the root directory which may have a
// limit on the number of files.
String directoryName = Environment.getExternalStorageDirectory().toString() + "/DCIM";
File directory = new File(directoryName);
if (!directory.isDirectory()) {
if (!directory.mkdirs()) {
return false;
}
}
return directory.canWrite();
}
回答by KitKat
On jargonjustin's post:
在 jargonjustin 的帖子中:
File ImageManager.java
Method hasStorage-->
方法hasStorage-->
public static boolean hasStorage(boolean requireWriteAccess) {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
if (requireWriteAccess) {
boolean writable = checkFsWritable();
return writable;
} else {
return true;
}
} else if (!requireWriteAccess
&& Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
Method checkFsWritable-->
方法checkFsWritable-->
private static boolean checkFsWritable() {
// Create a temporary file to see whether a volume is really writeable.
// It's important not to put it in the root directory which may have a
// limit on the number of files.
String directoryName =
Environment.getExternalStorageDirectory().toString() + "/DCIM";
File directory = new File(directoryName);
if (!directory.isDirectory()) {
if (!directory.mkdirs()) {
return false;
}
}
File f = new File(directoryName, ".probe");
try {
// Remove stale file if any
if (f.exists()) {
f.delete();
}
if (!f.createNewFile()) {
return false;
}
f.delete();
return true;
} catch (IOException ex) {
return false;
}
}
回答by Neil Trodden
I apologise for posting a non-Android way of doing this, hopefully someone can provide an answer using the Android API.
我很抱歉发布了一种非 Android 的方法,希望有人可以使用 Android API 提供答案。
You could list the files on the root of the sdcard. If there is none, the sdcard is either entirely blank (unusual, but possible) or it is unmounted. If you try to create an empty file on the sdcard and it fails, it means that you were trying to create a file in the mount-point of the sdcard which would be denied due to a permissions issue so you would know the sdcard was not mounted.
您可以列出 SD 卡根目录上的文件。如果没有,则 SD 卡要么完全空白(不寻常,但可能),要么已卸载。如果您尝试在 sdcard 上创建一个空文件但失败了,这意味着您正在尝试在 sdcard 的挂载点中创建一个文件,该文件会因权限问题而被拒绝,因此您会知道该 sdcard 不是安装。
Yes, I know this is ugly....
是的,我知道这很丑……
回答by Harinder
public static boolean isSdPresent() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
回答by Paul
I was using cursor for retrieving the images from sd card and when no sd card was inserted in device the cursor was null. Actually this is the case when the sdcard volume was unmounted by physically removing card from device. This is the code I've used:
我使用光标从 sd 卡中检索图像,当设备中没有插入 sd 卡时,光标为空。实际上,这是通过从设备中物理移除卡来卸载 sdcard 卷的情况。这是我使用的代码:
Cursor mCursor = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (mCursor == null || !mCursor .moveToFirst()) {
/**
*mCursor == null:
* - query failed; the app don't have access to sdCard; example: no sdCard
*
*!mCursor.moveToFirst():
* - there is no media on the device
*/
} else {
// process the images...
mCursor.close();
}
More info: http://developer.android.com/guide/topics/media/mediaplayer.html#viacontentresolver
更多信息:http: //developer.android.com/guide/topics/media/mediaplayer.html#viacontentresolver
回答by Mahmoud
Before you do any work with the external storage, you should always call getExternalStorageState() to check whether the media is available. The media might be mounted to a computer, missing, read-only, or in some other state. For example, here are a couple methods you can use to check the availability:
在使用外部存储进行任何工作之前,您应该始终调用 getExternalStorageState() 来检查媒体是否可用。介质可能已安装到计算机、丢失、只读或处于其他某种状态。例如,您可以使用以下几种方法来检查可用性:
/* 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;
}
source: http://developer.android.com/guide/topics/data/data-storage.html
来源:http: //developer.android.com/guide/topics/data/data-storage.html
回答by Sam
Cool....Check it out...
try {
File mountFile = new File("/proc/mounts");
usbFoundCount=0;
sdcardFoundCount=0;
if(mountFile.exists())
{
Scanner usbscanner = new Scanner(mountFile);
while (usbscanner.hasNext()) {
String line = usbscanner.nextLine();
if (line.startsWith("/dev/fuse /storage/usbcard1")) {
usbFoundCount=1;
Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/usbcard1" );
}
}
}
if(mountFile.exists()){
Scanner sdcardscanner = new Scanner(mountFile);
while (sdcardscanner.hasNext()) {
String line = sdcardscanner.nextLine();
if (line.startsWith("/dev/fuse /storage/sdcard1")) {
sdcardFoundCount=1;
Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/sdcard1" );
}
}
}
if(usbFoundCount==1)
{
Toast.makeText(context,"USB Connected and properly mounted", 7000).show();
Log.i("-----USB--------","USB Connected and properly mounted" );
}
else
{
Toast.makeText(context,"USB not found!!!!", 7000).show();
Log.i("-----USB--------","USB not found!!!!" );
}
if(sdcardFoundCount==1)
{
Toast.makeText(context,"SDCard Connected and properly mounted", 7000).show();
Log.i("-----SDCard--------","SDCard Connected and properly mounted" );
}
else
{
Toast.makeText(context,"SDCard not found!!!!", 7000).show();
Log.i("-----SDCard--------","SDCard not found!!!!" );
}
}catch (Exception e) {
e.printStackTrace();
}