以编程方式检查 SD 卡是否可用

发布于 2024-12-04 20:10:36 字数 89 浏览 1 评论 0 原文

我的应用程序适用于仅具有 SD 卡的手机。因此,我想以编程方式检查 SD 卡是否可用以及如何找到 SD 卡可用空间。是否可以?

如果是,我该怎么做?

My app is working for mobiles which have an SD card only. So programmatically I want to check if the SD card is available or not and how to find the SD card free space. Is it possible?

If yes, how do I do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

夢归不見 2024-12-11 20:10:36
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
}
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
}
心凉怎暖 2024-12-11 20:10:36

接受的答案对我不起作用

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

如果设备有内置存储,它会返回 true;
我的解决方案是检查外部文件目录数,如果有多个,则设备有SD卡。
它有效,并且我在多种设备上测试了它。

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

Accepted answer doesn't work for me

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

In case if device has a built-in storage, it returns true;
My solution is that to check the external files directory count, if there is more than one, device has sdcard.
It works and I tested it for several devices.

public static boolean hasRealRemovableSdCard(Context context) {
    return ContextCompat.getExternalFilesDirs(context, null).length >= 2;
}
我是男神闪亮亮 2024-12-11 20:10:36

您可以像这样检查外部可移动 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;

}

正如我测试过的那样,它工作得很好。

You can check if external removable sd card is available like this

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;

}

This works perfectly as i have tested it.

开始看清了 2024-12-11 20:10:36

按照 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();

Use Environment.getExternalStorageState() as described in "Using the External Storage".

To get available space on external storage, use 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();
怂人 2024-12-11 20:10:36

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

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

I wrote a little class for that checking the storage state. Maybe it's of some use for you.

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;
}
}
}
作妖 2024-12-11 20:10:36

我修改了它,如果 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";
}

I modified it such that if an SD card exists, it sets the path there. If not, it sets it at the internal directory.

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent)
{
    path = theAct.getExternalCacheDir().getAbsolutePath() + "/GrammarFolder";
}
else
{
    path = theAct.getFilesDir() + "/GrammarFolder";
}
怼怹恏 2024-12-11 20:10:36
 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);
}
 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);
}
尘曦 2024-12-11 20:10:36

这个简单的方法对我来说很有效。在所有类型的设备中进行了测试。

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

This simple method is worked for me. Tested in all type of devices.

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;
    }
  }
梦旅人picnic 2024-12-11 20:10:36

科特林

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

Kotlin

fun Context.externalMemoryAvailable(): Boolean {
    val storages = ContextCompat.getExternalFilesDirs(this, null)
    return storages.size > 1 && storages[0] != null && storages[1] != null
}
娇柔作态 2024-12-11 20:10:36
  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;
   }
  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;
   }
芯好空 2024-12-11 20:10:36

我创建了一个类来检查 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);
    }
}

I created a class to check if the folder on the SD card is available or not:

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);
    }
}
半窗疏影 2024-12-11 20:10:36
** 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");

            }
** i fixed this with help of @Jemo Mgebrishvili answer** 

this works perfectly even if sd card is present and in the ejected state

 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");

            }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文