您的位置:首页 > 移动开发 > Android开发

Android外部应用获取SD卡状态

2016-07-01 10:35 441 查看
像是从android4.0以后,外部应用就无法通过android标准接口获取到SD卡状态,但是可以通过如下方法获取:

1. 通过env 获取SD卡路径

 String externalStorage = System.getenv("SECONDARY_STORAGE");​

​2. 通过读取mounts节点获取SD卡挂载状态

private boolean isSdcardMounted(){

    boolean mounted = false;

    String line = null;

    BufferedReader reader = null;

    try{

        reader = new BufferedReader(new FileReader("/proc/mounts"));

        if(reader == null){

            return mounted;

        }

        while ((line = reader.readLine()) != null) {

            String[] tmp = line.split(" ");

            if(tmp.length >= 2){

                if(tmp[1] != null&& tmp[1].equals("/storage/sdcard1")){

                    mounted = true;

                    break;

                }

            }

        }

    }catch(FileNotFoundException e){

    }catch(IOException ee){

    }finally{

        try{

            if(reader != null)

                reader.close();

        }catch(IOException eee){

        }

    }

    Log.d(TAG,"isSdcardMounted mounted:"+mounted);

    return mounted;

}

​3. SD卡剩余空间获取

private int getSdcardFreeSpace(){//unit is Million

    int space = 0;

    File file = new File("/storage/sdcard1");

    if(file.exists()){

        long freeSize = file.getUsableSpace();

        space = (int)(freeSize/1024/1024);

    }

    Log.d(TAG,"getSdcardFreeSpace :"+space);

    return space; 

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: