【问题标题】:Check whether the SD card is available or not programmatically以编程方式检查 SD 卡是否可用
【发布时间】:2011-11-17 18:11:11
【问题描述】:

我的应用适用于只有 SD 卡的手机。所以我想以编程方式检查 SD 卡是否可用以及如何找到 SD 卡的可用空间。有可能吗?

如果是,我该怎么做?

【问题讨论】:

  • “仅限 SD 卡”是什么意思?你的意思是它没有内部存储器?这很难想象。

标签: android sd-card


【解决方案1】:
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
Boolean isSDSupportedDevice = Environment.isExternalStorageRemovable();

if(isSDSupportedDevice && isSDPresent)
{
  // yes SD-card is present
}
else
{
 // Sorry
}

【讨论】:

  • 如何查看sdcard空闲内存?
  • 但如果手机有内置存储,它会返回 true..所以不是正确的答案
  • 在现代 Android 设备上,外部存储(称为“sdcard”)现在也可以是内部存储,只是分开。所以是的,这是一个很好的答案。
  • 要确定外部存储是否是 SDCARD,请结合使用上述内容:Environment.isExternalStorageRemovable()
  • 在模拟外部存储的情况下,这显然是一个错误的答案。理想情况下,应使用 Environment.isExternalStorageRemovable()。您还可以看到 Environment.isExternalStorageEmulated()。 @naresh 你不应该接受部分答案。
【解决方案2】:

接受的答案对我不起作用

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

如果设备有内置存储,则返回true; 我的解决方案是检查外部文件目录数,如果有多个,则设备有sdcard。 它工作正常,我在几台设备上对其进行了测试。

public static boolean hasRealRemovableSdCard(Context context) {
    return ContextCompat.getExternalFilesDirs(context, null).length >= 2;
}

【讨论】:

  • 但是如果设备有槽并且没有插入sd卡,则显示长度为2。文件数组有空文件。无论如何,这对我来说是最好的解决方案:)
【解决方案3】:

您可以像这样检查外部可移动 sd 卡是否可用

public static boolean externalMemoryAvailable(Activity context) {
    File[] storages = ContextCompat.getExternalFilesDirs(context, null);
    if (storages.length > 1 && storages[0] != null && storages[1] != null)
        return true;
    else
        return false;

}

我已经测试过了,这非常有效。

【讨论】:

  • 我已经在三星 A70s 上测试过,无论有没有外接(可移动)SD 卡,在这两种情况下,它都运行良好。我已经尝试了其他人建议的所有解决方案,但这个工作正常。希望也适用于所有设备。非常感谢。
【解决方案4】:

按照"Using the External Storage" 中的说明使用Environment.getExternalStorageState()

要获得外部存储的可用空间,请使用StatFs

// do this only *after* you have checked external storage state:
File extdir = Environment.getExternalStorageDirectory();
File stats = new StatFs(extdir.getAbsolutePath());
int availableBytes = stats.getAvailableBlocks() * stats.getBlockSize();

【讨论】:

    【解决方案5】:

    我写了一个小类来检查存储状态。或许对你有用。

    import android.os.Environment;
    
    /**
     * Checks the state of the external storage of the device.
     * 
     * @author kaolick
     */
    public class StorageHelper
    {
    // Storage states
    private boolean externalStorageAvailable, externalStorageWriteable;
    
    /**
     * Checks the external storage's state and saves it in member attributes.
     */
    private void checkStorage()
    {
    // Get the external storage's state
    String state = Environment.getExternalStorageState();
    
    if (state.equals(Environment.MEDIA_MOUNTED))
    {
        // Storage is available and writeable
        externalStorageAvailable = externalStorageWriteable = true;
    }
    else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY))
    {
        // Storage is only readable
        externalStorageAvailable = true;
        externalStorageWriteable = false;
    }
    else
    {
        // Storage is neither readable nor writeable
        externalStorageAvailable = externalStorageWriteable = false;
    }
    }
    
    /**
     * Checks the state of the external storage.
     * 
     * @return True if the external storage is available, false otherwise.
     */
    public boolean isExternalStorageAvailable()
    {
    checkStorage();
    
    return externalStorageAvailable;
    }
    
    /**
     * Checks the state of the external storage.
     * 
     * @return True if the external storage is writeable, false otherwise.
     */
    public boolean isExternalStorageWriteable()
    {
    checkStorage();
    
    return externalStorageWriteable;
    }
    
    /**
     * Checks the state of the external storage.
     * 
     * @return True if the external storage is available and writeable, false
     *         otherwise.
     */    
    public boolean isExternalStorageAvailableAndWriteable()
    {
    checkStorage();
    
    if (!externalStorageAvailable)
    {
        return false;
    }
    else if (!externalStorageWriteable)
    {
        return false;
    }
    else
    {
        return true;
    }
    }
    }
    

    【讨论】:

    • 这个 calss 是否有助于检测 sd 卡的可用性?
    • @PankajNimgade 此类可帮助您检查外部存储是否可用和/或可写。外部存储设备可以是 SD 卡或内置存储设备,如 nexus 设备。
    • 是否可以专门检查“sdcard”?提前谢谢
    • @PankajNimgade 我不知道。我建议在这里阅读有关内部和外部存储的信息:developer.android.com/guide/topics/data/data-storage.html
    • 浏览过该文件和其他几个文件,google 对“设备上可用的外部存储”和“sd 卡”没有具体的区别...... :(
    【解决方案6】:

    我对其进行了修改,如果存在 SD 卡,它将在那里设置路径。如果不是,则将其设置在内部目录中。

    Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    if(isSDPresent)
    {
        path = theAct.getExternalCacheDir().getAbsolutePath() + "/GrammarFolder";
    }
    else
    {
        path = theAct.getFilesDir() + "/GrammarFolder";
    }
    

    【讨论】:

      【解决方案7】:
       void updateExternalStorageState() {
           String state = Environment.getExternalStorageState();
           if (Environment.MEDIA_MOUNTED.equals(state)) {
              mExternalStorageAvailable = mExternalStorageWriteable = true;
           } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
              mExternalStorageAvailable = true;
             mExternalStorageWriteable = false;
           } else {
             mExternalStorageAvailable = mExternalStorageWriteable = false;
      }
      handleExternalStorageState(mExternalStorageAvailable,
              mExternalStorageWriteable);
      }
      

      【讨论】:

        【解决方案8】:

        这个简单的方法对我有用。在所有类型的设备中测试。

        public boolean externalMemoryAvailable() {
            if (Environment.isExternalStorageRemovable()) {
              //device support sd card. We need to check sd card availability.
              String state = Environment.getExternalStorageState();
              return state.equals(Environment.MEDIA_MOUNTED) || state.equals(
                  Environment.MEDIA_MOUNTED_READ_ONLY);
            } else {
              //device not support sd card. 
              return false;
            }
          }
        

        【讨论】:

          【解决方案9】:

          科特林

          fun Context.externalMemoryAvailable(): Boolean {
              val storages = ContextCompat.getExternalFilesDirs(this, null)
              return storages.size > 1 && storages[0] != null && storages[1] != null
          }
          

          【讨论】:

            【解决方案10】:
              public static boolean hasSdCard(Context context) {
            
                File[] dirs = context.getExternalFilesDirs("");        
                if(dirs.length >= 2 && dirs[1]!=null){
                    if(Environment.isExternalStorageRemovable(dirs[1])){ // Extra Check
                        return true;
                    }
                 }
                return false;
               }
            

            【讨论】:

              【解决方案11】:

              我创建了一个类来检查 SD 卡上的文件夹是否可用:

              public class GetFolderPath {
              
                  static String folderPath;
              
                  public static String getFolderPath(Context context) {
                      if (isSdPresent() == true) {
                          try {
                              File sdPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/FolderName");
                              if(!sdPath.exists()) {
                                  sdPath.mkdirs();
                                  folderPath = sdPath.getAbsolutePath();
                              } else if (sdPath.exists()) {
                                  folderPath = sdPath.getAbsolutePath();
                              }
                          }
                          catch (Exception e) {
              
                          }
                          folderPath = Environment.getExternalStorageDirectory().getPath()+"/FolderName/";
                      }
                      else {
                          try {
                              File cacheDir=new File(context.getCacheDir(),"FolderName/");
                              if(!cacheDir.exists()) {
                                  cacheDir.mkdirs();
                                  folderPath = cacheDir.getAbsolutePath();
                              } else if (cacheDir.exists()) {
                                  folderPath = cacheDir.getAbsolutePath();
                              }
                          }
                          catch (Exception e){
              
                          }
                      }
                      return folderPath;
                  }
              
                  public static boolean isSdPresent() {
                      return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
                  }
              }
              

              【讨论】:

                【解决方案12】:
                ** i fixed this with help of @Jemo Mgebrishvili answer** 
                

                即使存在 sd 卡并且处于弹出状态,这也能完美运行

                 if (ContextCompat.getExternalFilesDirs(this, null).length >= 2) {
                                File[] f = ContextCompat.getExternalFilesDirs(this, null);
                                for (int i = 0; i < f.length; i++) {
                                    File file = f[i];
                                    if(file!=null && i ==1)
                                    {
                                        Log.d(TAG,file.getAbsolutePath()+ "external sd card  available");
                
                                    }
                
                                }
                            } else {
                                Log.d(TAG, " external sd card not available");
                
                            }
                

                【讨论】:

                  猜你喜欢
                  • 2016-04-15
                  • 1970-01-01
                  • 2012-01-10
                  • 1970-01-01
                  • 2012-11-18
                  • 1970-01-01
                  • 2022-01-22
                  • 2013-10-23
                  • 2015-02-26
                  相关资源
                  最近更新 更多