android获取内置和外置SD卡路径

本文将介绍android真机环境下如何获取内置和外置SD卡路径。


测试环境:三星Note3,其他手机待测试。。。


所需权限(AndroidManifest.xml文件里)


获取路径代码(MainActivity.java文件)

package com.example.androidtest;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		StringBuilder log = new StringBuilder();
		String inPath = getInnerSDCardPath();
		log.append("内置SD卡路径:" + inPath + "\r\n");
		
		List extPaths = getExtSDCardPath();
		for (String path : extPaths) {
			log.append("外置SD卡路径:" + path + "\r\n");
		}
		System.out.println(log.toString());
	}
	
	/**
	 * 获取内置SD卡路径
	 * @return
	 */
	public String getInnerSDCardPath() {  
        return Environment.getExternalStorageDirectory().getPath();  
    }

	/**
	 * 获取外置SD卡路径
	 * @return	应该就一条记录或空
	 */
	public List getExtSDCardPath()
	{
		List lResult = new ArrayList();
		try {
			Runtime rt = Runtime.getRuntime();
			Process proc = rt.exec("mount");
			InputStream is = proc.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line;
			while ((line = br.readLine()) != null) {
				if (line.contains("extSdCard"))
				{
					String [] arr = line.split(" ");
					String path = arr[1];
					File file = new File(path);
					if (file.isDirectory())
					{
						lResult.add(path);
					}
				}
			}
			isr.close();
		} catch (Exception e) {
		}
		return lResult;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

其中,line.contains("extSdCard")判断部分有待进一步验证!


打印结果:

1. 插入一张外置SD卡后

内置SD卡路径:/storage/emulated/0
外置SD卡路径:/storage/extSdCard

2. 取出外置SD卡后

内置SD卡路径:/storage/emulated/0




你可能感兴趣的:(android)