有没有一种通用的方法来找到外置SD卡的位置?
请不要与外部存储混淆。
Environment.getExternalStorageState()返回内部SD挂载点的路径,例如/mnt/sdcard。但问题是关于外部SD的。我如何获得类似/mnt/sdcard/external_sd的路径(它可能因设备而异)?
我想我将以根据文件系统名称过滤mount命令的输出作为结束。但我不确定这种方式是否足够稳健。
有没有一种通用的方法来找到外置SD卡的位置?
请不要与外部存储混淆。
Environment.getExternalStorageState()返回内部SD挂载点的路径,例如/mnt/sdcard。但问题是关于外部SD的。我如何获得类似/mnt/sdcard/external_sd的路径(它可能因设备而异)?
我想我将以根据文件系统名称过滤mount命令的输出作为结束。但我不确定这种方式是否足够稳健。
当前回答
我已经创建了一个utils方法来检查SD卡在设备上是否可用,并获得设备上的SD卡路径(如果可用)。
你可以复制2方法波纹到你的项目的类,你需要。这是所有。
public String isRemovableSDCardAvailable() {
final String FLAG = "mnt";
final String SECONDARY_STORAGE = System.getenv("SECONDARY_STORAGE");
final String EXTERNAL_STORAGE_DOCOMO = System.getenv("EXTERNAL_STORAGE_DOCOMO");
final String EXTERNAL_SDCARD_STORAGE = System.getenv("EXTERNAL_SDCARD_STORAGE");
final String EXTERNAL_SD_STORAGE = System.getenv("EXTERNAL_SD_STORAGE");
final String EXTERNAL_STORAGE = System.getenv("EXTERNAL_STORAGE");
Map<Integer, String> listEnvironmentVariableStoreSDCardRootDirectory = new HashMap<Integer, String>();
listEnvironmentVariableStoreSDCardRootDirectory.put(0, SECONDARY_STORAGE);
listEnvironmentVariableStoreSDCardRootDirectory.put(1, EXTERNAL_STORAGE_DOCOMO);
listEnvironmentVariableStoreSDCardRootDirectory.put(2, EXTERNAL_SDCARD_STORAGE);
listEnvironmentVariableStoreSDCardRootDirectory.put(3, EXTERNAL_SD_STORAGE);
listEnvironmentVariableStoreSDCardRootDirectory.put(4, EXTERNAL_STORAGE);
File externalStorageList[] = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
externalStorageList = getContext().getExternalFilesDirs(null);
}
String directory = null;
int size = listEnvironmentVariableStoreSDCardRootDirectory.size();
for (int i = 0; i < size; i++) {
if (externalStorageList != null && externalStorageList.length > 1 && externalStorageList[1] != null)
directory = externalStorageList[1].getAbsolutePath();
else
directory = listEnvironmentVariableStoreSDCardRootDirectory.get(i);
directory = canCreateFile(directory);
if (directory != null && directory.length() != 0) {
if (i == size - 1) {
if (directory.contains(FLAG)) {
Log.e(getClass().getSimpleName(), "SD Card's directory: " + directory);
return directory;
} else {
return null;
}
}
Log.e(getClass().getSimpleName(), "SD Card's directory: " + directory);
return directory;
}
}
return null;
}
/**
* Check if can create file on given directory. Use this enclose with method
* {@link BeginScreenFragement#isRemovableSDCardAvailable()} to check sd
* card is available on device or not.
*
* @param directory
* @return
*/
public String canCreateFile(String directory) {
final String FILE_DIR = directory + File.separator + "hoang.txt";
File tempFlie = null;
try {
tempFlie = new File(FILE_DIR);
FileOutputStream fos = new FileOutputStream(tempFlie);
fos.write(new byte[1024]);
fos.flush();
fos.close();
Log.e(getClass().getSimpleName(), "Can write file on this directory: " + FILE_DIR);
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Write file error: " + e.getMessage());
return null;
} finally {
if (tempFlie != null && tempFlie.exists() && tempFlie.isFile()) {
// tempFlie.delete();
tempFlie = null;
}
}
return directory;
}
其他回答
通过读取/proc/mounts(标准的Linux文件),并对vold数据(/system/etc/vold.conf)进行交叉检查,可以找到任何其他SD卡被挂载的位置。注意,Environment.getExternalStorageDirectory()返回的位置可能不会出现在vold配置中(在某些设备中,它是不能卸载的内部存储),但仍然必须包含在列表中。然而,我们并没有找到一个向用户描述它们的好方法。
我不知道为什么,但我需要在使用它之前在公共存储目录中创建的文件上调用. createnewfile()。在框架中,该方法的注释说它没有用。这是一个样本……
String myPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS) + File. txt文件。separator +“我的目录”; final File myDir = new File(myypath); 尝试{ myDir.mkdirs (); } catch(异常ex) { 吐司。makeText(this, "error: " + ex.getMessage(), Toast.LENGTH_LONG).show(); }
String fname = "whatever";
File newFile = new File(myDir, fname);
Log.i(TAG, "File exists --> " + newFile.exists()) //will be false
try {
if (newFile.createNewFile()) {
//continue
} else {
Log.e(TAG, "error creating file");
}
} catch (Exception e) {
Log.e(TAG, e.toString());
}
由于上面我最初的回答,扫描vold在各个制造商中不再可行。
我发明了一种更可靠更直接的方法。
File mnt = new File("/storage");
if (!mnt.exists())
mnt = new File("/mnt");
File[] roots = mnt.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory() && pathname.exists()
&& pathname.canWrite() && !pathname.isHidden()
&& !isSymlink(pathname);
}
});
根目录将包含系统上所有可写的根目录,包括任何usb连接的usb设备。
注意:canWrite方法需要android.permission。WRITE_EXTERNAL_STORAGE许可。
这个解决方案处理System.getenv(“SECONDARY_STORAGE”)在Marshmallow中没有用的问题。
已测试和正在进行:
Samsung Galaxy Tab 2 (Android 4.1.1 - Stock) Samsung Galaxy Note 8.0 (Android 4.2.2 - Stock) Samsung Galaxy S4 (Android 4.4 - Stock) Samsung Galaxy S4 (Android 5.1.1 - Cyanogenmod) Samsung Galaxy Tab A (Android 6.0.1 - Stock) /** * Returns all available external SD-Card roots in the system. * * @return paths to all available external SD-Card roots in the system. */ public static String[] getStorageDirectories() { String [] storageDirectories; String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { List<String> results = new ArrayList<String>(); File[] externalDirs = applicationContext.getExternalFilesDirs(null); for (File file : externalDirs) { String path = file.getPath().split("/Android")[0]; if((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Environment.isExternalStorageRemovable(file)) || rawSecondaryStoragesStr != null && rawSecondaryStoragesStr.contains(path)){ results.add(path); } } storageDirectories = results.toArray(new String[0]); }else{ final Set<String> rv = new HashSet<String>(); if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) { final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator); Collections.addAll(rv, rawSecondaryStorages); } storageDirectories = rv.toArray(new String[rv.size()]); } return storageDirectories; }
Environment.getExternalStorageState()返回内部SD挂载点的路径,如"/mnt/sdcard"
不,Environment.getExternalStorageDirectory()指的是设备制造商认为是“外部存储”的任何东西。在某些设备上,这是可移动媒体,如SD卡。在某些设备上,这是设备上flash的一部分。这里的“外部存储”指的是“挂载在主机上通过USB大容量存储模式访问的东西”,至少对于Android 1来说是这样。X和2.x。
但问题是关于外置SD。如何获得像“/mnt/sdcard/external_sd”这样的路径(它可能因设备而异)?
Android没有“外部SD”的概念,除了如上所述的外部存储。
如果设备制造商已经选择将外部存储作为板载闪存,并且还具有SD卡,那么您将需要联系该制造商以确定是否可以使用SD卡(不保证)以及使用它的规则,例如使用它的路径。
更新
最近有两件事值得注意:
首先,在Android 4.4+上,你没有对可移动媒体(例如,“外部SD”)的写访问权,除非该媒体上的任何位置可能由getExternalFilesDirs()和getExternalCacheDirs()返回。请参阅Dave Smith对此的出色分析,特别是如果您想了解底层细节的话。
其次,为了避免有人质疑可移动媒体访问是否是Android SDK的一部分,以下是Dianne Hackborn的评估:
...keep in mind: until Android 4.4, the official Android platform has not supported SD cards at all except for two special cases: the old school storage layout where external storage is an SD card (which is still supported by the platform today), and a small feature added to Android 3.0 where it would scan additional SD cards and add them to the media provider and give apps read-only access to their files (which is also still supported in the platform today). Android 4.4 is the first release of the platform that has actually allowed applications to use SD cards for storage. Any access to them prior to that was through private, unsupported APIs. We now have a quite rich API in the platform that allows applications to make use of SD cards in a supported way, in better ways than they have been able to before: they can make free use of their app-specific storage area without requiring any permissions in the app, and can access any other files on the SD card as long as they go through the file picker, again without needing any special permissions.