首页 > 代码库 > Android各种机型,各种系统版本,如何获取外置SDCard路径

Android各种机型,各种系统版本,如何获取外置SDCard路径

由于项目需要,在有外置sdcard的情况下,可能不希望直接将应用内数据存入内置sdcard,我于是专门写了一个函数来获取sdcard路径

如果有外置sdcard就获取外置sdcard,如果没有就用系统默认的"外置sdcard"(深入研究可能知道,这个外置sdcard实际是从内置sdcard里面分出来的一个分区而已)

下面直接上代码:

public static String getSDCardPath(){
		String cmd = "cat /proc/mounts";
        Runtime run = Runtime.getRuntime();
        BufferedInputStream in=null;
        BufferedReader inBr=null;
        try {
            Process p = run.exec(cmd);
            in = new BufferedInputStream(p.getInputStream());
            inBr = new BufferedReader(new InputStreamReader(in));

            String lineStr;
            while ((lineStr = inBr.readLine()) != null) {
            Log.i("CommonUitls", lineStr);
                if (lineStr.toLowerCase().contains("sdcard".toLowerCase())
                        && lineStr.contains(".android_secure")) {
                    String[] strArray = lineStr.split(" ");
                    if (strArray != null && strArray.length >= 5) {
                        String result = strArray[1].replace("/.android_secure",
                                "");
                        Log.i("CommonUitls", result);
                        return result;
                    }
                }
                if(lineStr.toLowerCase().contains("extsd".toLowerCase())){
                	String[] strArray = lineStr.split(" ");
                	Log.i("CommonUitls", strArray[1]);
                	return strArray[1];
                }
                if (p.waitFor() != 0 && p.exitValue() == 1) {
                	Log.e("CommonUitls", "CMD cat /proc/mounts ERROR!");
                }
            }
        } catch (Exception e) {
        	e.printStackTrace();
        	Log.e("CommonUitls", e.toString());
        }finally{
            try {
	            if(in!=null){
	               in.close();
	            }
            } catch (IOException e) {
            	// TODO Auto-generated catch block
            	e.printStackTrace();
            	Log.e("CommonUitls", e.toString());
            }
		    try {
		        if(inBr!=null){
		        	inBr.close();
		         }
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.e("CommonUitls", e.toString());
			}
	    }
        return Environment.getExternalStorageDirectory().getPath();
	}


Android各种机型,各种系统版本,如何获取外置SDCard路径