1设置sdk版本
compileSdkVersion 30
minSdkVersion 23
targetSdkVersion 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("请获取权限");
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
return true;
} else {
return false;
}
}
具体使用:
public final static String DOWNLOAD_DIR = Environment.getExternalStorageDirectory().getPath() + "/Download";
if (Authority.file(activity) == false) {
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();
}
|