博观而约取,厚积而薄发。这篇文章主要讲述android获取内置和外置SD卡路径 - z相关的知识,希望能为你提供帮助。
【android获取内置和外置SD卡路径 - z】本文将介绍Android真机环境下如何获取内置和外置SD卡路径。
测试环境:三星Note3,其他手机待测试。。。
所需权限(androidManifest.xml文件里)
[html]
view plain
copy
- < uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
获取路径代码(MainActivity.java文件)
[java] view plain copy
- 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< String> 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< String> getExtSDCardPath()
- {
- List< String> lResult = new ArrayList< String> ();
- 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卡后
[plain] view plain copy
- 内置SD卡路径:/storage/emulated/0
- 外置SD卡路径:/storage/extSdCard
2. 取出外置SD卡后
[plain] view plain copy
- 内置SD卡路径:/storage/emulated/0
推荐阅读
- spring配置文件applicationContext.xml的路径设置
- Android开发艺术探索
- React-Native 问题随记2( com.android.builder.testing.api.DeviceException)
- Android中让应用程序自动安装到手机内存及判断应用程序是否安装在SDCard中
- Android 进制互相转换
- 深入理解android view 生命周期
- Android零基础入门第44节(ListView数据动态更新)
- 智能家居控制APPUI界面设计
- Eclipse 远程调试 WebSphere Application Server (WAS)