原文连接
不同版本的安卓获取数据方式不一样
- List item
/**- 6.0使用此方法获取外置SD卡路径,尝试过反射
- 但StorageVolume非Public API 编译不通过(7.0改为公开API),故使用UserEnvironment
- 的内部方法getExternalDirs获取所有的路径,通过{@link Environment#isExternalStorageRemovable(File)}
- 判断若removable则为外部存储
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static String getPhysicalExternalFilePathAboveM(){
try {
//===获取UserEnvironment
Class<?> userEnvironment = Class.forName(“android.os.Environment$UserEnvironment”);
Method getExternalDirs =userEnvironment.getDeclaredMethod(“getExternalDirs”);
getExternalDirs.setAccessible(true);
//获取构造UserEnvironment的必要参数UserId
Class<?> userHandle = Class.forName(“android.os.UserHandle”);
Method myUserId = userHandle.getDeclaredMethod(“myUserId”);
myUserId.setAccessible(true);
int mUserId = (int) myUserId.invoke(UserHandle.class);
Constructor<?> declaredConstructor = userEnvironment.getDeclaredConstructor(Integer.TYPE);
// 得到UserEnvironment instance
Object instance = declaredConstructor.newInstance(mUserId);
File[] files = (File[]) getExternalDirs.invoke(instance);
for (int i = 0; i < files.length; i++) {
if (Environment.isExternalStorageRemovable(files[i])){
return files[i].getPath();
}
}
} catch (Exception e) {
Log.e(TAG,e.getMessage());
}
return “”;
}
public static boolean copyFile(String source, String dest) {
try {
Log.e(TAG, “save 进入保存数据库方法 保存路劲=”+dest);
File f1 = new File(source);
File f0 = new File(dest);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f0);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, “copyFile保存数据库结果为false”,e);
}
return true;
}