【问题标题】:How to tell if the sdcard is mounted in Android?如何判断 sdcard 是否安装在 Android 中?
【发布时间】:2010-10-28 11:24:22
【问题描述】:

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

有没有人知道一种方法来判断 USB 是否已安装,以便我可以弹出一条消息通知用户它无法工作?

【问题讨论】:

  • 仅作记录,插入 USB 电缆并不是卸载 sdcard 卷的唯一方法 - 在存储设置中卸载卡或物理移除卡也可以。此外,t-mobile uk 提供的 8GB sdcard 未正确预格式化,因此由于 I/O,只要未正确重新格式化,它们就会一直被卸载。我之所以这么说,是因为有时仅仅告诉用户拔掉电缆是不够的。

标签: android android-sdcard


【解决方案1】:

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

如果您仍需要访问 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;
}

【讨论】:

  • 嗬,有人提供了android api的做事方式。投票!
  • 方法checkFsWritable();在哪里?
  • 我们是否需要<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 才能使其在外部存储上运行?
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    对于发布非 Android 方式的做法,我深表歉意,希望有人可以使用 Android API 提供答案。

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

    是的,我知道这很丑……

    【讨论】:

      【解决方案4】:
      public static boolean isSdPresent() {
      
      return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
      
      }
      

      【讨论】:

      • @MartinSmith 来源也有我
      【解决方案5】:

      关于 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;
              }
          }
      

      【讨论】:

        【解决方案6】:

        我使用光标从 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(); 
            }
        

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

        【讨论】:

          【解决方案7】:

          在对外部存储进行任何操作之前,您应该始终调用 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

          【讨论】:

            【解决方案8】:
            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();
                    } 
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-07-09
              • 1970-01-01
              • 1970-01-01
              • 2013-10-26
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多