问题主要出现在以下代码中
static long getSDTotalSize(@NonNull Context context) {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return blockSize * totalBlocks;
}
部分手机获取到sd卡路径是无效的,猜测就是手机无sdCard,往下追源码发现StatFs构造方法中,调用了doStat(path)方法,
而在此方法中,如果sd卡路径是无效的,就会抛出异常java.lang.IllegalArgumentException: Invalid path: /storage/emulated/0
/**
* Construct a new StatFs for looking at the stats of the filesystem at
* {@code path}. Upon construction, the stat of the file system will be
* performed, and the values retrieved available from the methods on this
* class.
*
* @param path path in the desired file system to stat.
*
* @throws IllegalArgumentException if the file system access fails
*/
public StatFs(String path) {
mStat = doStat(path);
}
/**
* @throws IllegalArgumentException if the file system access fails
*/
private static StructStatVfs doStat(String path) {
try {
return Os.statvfs(path);
} catch (ErrnoException e) {
throw new IllegalArgumentException("Invalid path: " + path, e);
}
}
解决办法:
使用try catch
static long getSDTotalSize(@NonNull Context context) {
try {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return blockSize * totalBlocks;
}catch (Exception e){
}
return 0;
}