该例实现的是后端返回的base64的字符串,里面包含图片和文字数据,保存为pdf到手机内存。
1、添加权限
<!-- 在cd卡中创建和删除的权限·-->
<uses-permission android:name="permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 读外存-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--用于写入缓存数据到扩展存储卡,需经动态申请-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2、在application中添加可分区存储的属性
android:requestLegacyExternalStorage="true"
3、动态申请写入数据到存储卡的权限
/**
* 检查是否享有写入外存的权限
*/
private void StartCheckWriteExternalPermission() {
if (PermissionChecker.checkSelfPermission(JSBridge.getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(JSBridge.getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, SAVE_PDF_EXTER_PERMISSION);
} else {//已经有权限
startDowloadPdf();//开始下载
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == SAVE_PDF_EXTER_PERMISSION) {//存外存权限
int length = Math.min(permissions.length, grantResults.length);
for (int i = 0; i < length; i++) {
if (TextUtils.equals(permissions[i], Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(JSBridge.getActivity(), "下载失败,请先前往设置打开存储权限", Toast.LENGTH_SHORT).show();
} else {
startDowloadPdf();//开始下载
}
break;
}
}
}
4、下载代码
/**
* 下载pdf
*/
private void startDowloadPdf() {
JSONObject returnBody=new JSONObject();
String fileBase64=savePdfJson.getString("fileBase64");
BufferedInputStream bis=null;
FileOutputStream fos=null;
BufferedOutputStream bos=null;
try {
fileBase64=fileBase64.replaceAll("^data:[a-zA-Z]+/[a-zA-Z]+;base64,", "");//此部分因传过来的数据有前缀而写,可忽略
byte[] bytes=Base64Util.decode(fileBase64);//将给定的Base64编码的字符串解码为一个新的字节数组,此为自己实现的工具类方法
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(bytes);
bis=new BufferedInputStream(byteArrayInputStream);
Date date=new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String currentData= dateFormat.format(date);
path1=Environment.getExternalStorageDirectory().getPath()+"/"+currentData;
File file=new File(path1+"/"+"xx.pdf");
File path = file.getParentFile();
if (!path.exists()) {
path.mkdirs();//创建多层目录
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int length = bis.read(buffer);
while (length != -1) {
bos.write(buffer, 0, length);
length = bis.read(buffer);
}
bos.flush();
Toast.makeText(JSBridge.getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
} catch (IOException e) {//失败
Toast.makeText(JSBridge.getActivity(), "保存失败", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} finally {
try {
bis.close();
bos.close();
fos.close();
} catch (IOException e) {//下载失败
Toast.makeText(JSBridge.getActivity(),"保存失败", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
完结。