如何判断SD卡是否已安装在Android中?

时间:2009-05-23 18:09:15

标签: android android-sdcard

我正在开发一个Android应用程序,需要查看用户存储的图像。问题是如果用户通过USB线安装了SD卡,我就无法读取磁盘上的图像列表。

有没有人知道如何判断usb是否已安装,以便我可以弹出一条消息通知用户它不起作用?

8 个答案:

答案 0 :(得分:38)

如果您尝试访问设备上的图片,最好的方法是使用MediaStore content provider。以content provider访问它将允许您查询存在的图像,并在适当的位置将content:// URL映射到设备上的文件路径。

如果您仍然需要访问SD卡,则相机应用程序包含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;
}

答案 1 :(得分:9)

以下是jargonjustin帖子

中的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();
    }

答案 2 :(得分:1)

我为发布非Android方式而道歉,希望有人可以使用Android API提供答案。

您可以列出SD卡根目录下的文件。如果没有,则SD卡要么完全空白(不寻常,但可能),要么已卸载。如果您尝试在SD卡上创建一个空文件并且它失败,则表示您尝试在SD卡的挂载点中创建一个文件,该文件由于权限问题而被拒绝,因此您可能知道sdcard不是安装。

是的,我知道这很难看......

答案 3 :(得分:1)

public static boolean isSdPresent() {

return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

}

答案 4 :(得分:1)

关于jargonjustin的帖子:

档案ImageManager.java

  

方法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;
    }
  

方法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;
        }
    }

答案 5 :(得分:0)

我正在使用光标从SD卡中检索图像,当设备中没有插入SD卡时,光标为空。 实际上,当通过从设备上物理移除卡来卸载SD卡卷时就是这种情况。这是我用过的代码:

  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(); 
    }

更多信息:http://developer.android.com/guide/topics/media/mediaplayer.html#viacontentresolver

答案 6 :(得分:0)

在使用外部存储器进行任何操作之前,应始终调用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;
}

源: http://developer.android.com/guide/topics/data/data-storage.html

答案 7 :(得分:-1)

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();
        }