1设置sdk版本
compileSdkVersion 30// 最高兼容版本
minSdkVersion 23 //最低兼容版本
targetSdkVersion 24//安装应用程序的手机系统大于设置 如果小于24页面会不兼容部分手机不会充满屏幕 设置太高获取外部存储权限不够
2添加权限
<uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE” />
<uses-permission android:name=“android.permission.READ_EXTERNAL_STORAGE” />
<application
android:requestLegacyExternalStorage="true"
</application>
正常获取权限在android11中并不奏效需要动态获取权限贴上工具类:
public static boolean file(Activity activity) {
final int REQUEST_EXTERNAL_STORAGE = 1;
String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
int permission = ActivityCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ToastUntil.showToast("请获取权限");
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
return true;
} else {
return false;
}
}
具体使用:
//外部存储路径
public final static String DOWNLOAD_DIR = Environment.getExternalStorageDirectory().getPath() + "/Download";
//判断是否获取权限如果为true弹窗获取权限false为已获取可直接下载
if (Authority.file(activity) == false) {
//android11 app包目录下可随意存储但不方便查找
// ContextWrapper cw = new ContextWrapper(BaseApplication.getConText());
// File directory = cw.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(APIConfig.DOWNLOAD_DIR, filename);
if (file.exists()) {
file.delete();
}
try {
FileDownUntil.writeToLocal(file, is);
ToastUntil.showToast("下载成功,请到本地查看");
} catch (IOException e) {
LogUtil.e("filedownload", e.getMessage());
ToastUntil.showToast("下载失败");
e.printStackTrace();
}
}
贴上具体下载工具类代码:
public static void writeToLocal(File destination, InputStream input)
throws IOException {
int index;
byte[] bytes = new byte[1024];
FileOutputStream downloadFile = new FileOutputStream(destination);
while ((index = input.read(bytes)) != -1) {
downloadFile.write(bytes, 0, index);
downloadFile.flush();
}
input.close();
downloadFile.close();
}