okhttp下载文件并直接显示到手机上

如果调用okhttp工具类下载服务器文件报错

请按以下步骤检查:

1.动态申请权限,同时AndroidManifest.xml的application中添加

android:usesCleartextTraffic="true"

2.下载文件函数(downFile)在线程中调用

3.downFile的第二个参数文件路径写成相对路径(Environment.getExternalStorageDirectory() + "/download/")

 

相关代码:

public void checkPemission() {
Log.e("TAG", "进入了checkPemission()");
int hasWritePermission = PermissionChecker.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWritePermission != PermissionChecker.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 9);
} else {
new Thread() {
@Override
public void run() {
super.run();
downFile(urlString);
}
}.start();
}
}

/**
* 文件下载
*/
private void downFile(String url) {
DownloadUtil.get().download(url, Environment.getExternalStorageDirectory() + "/pdf/", "test.pdf",
new DownloadUtil.OnDownloadListener() {
@Override
public void onDownloadSuccess(File file) {

openPDF(file);//打开PDF文件
}

@Override
public void onDownloading(int progress) {

}

@Override
public void onDownloadFailed(Exception e) {
//下载异常进行相关提示操作

}
});
}


源码地址: 稍后附上

okhttp下载文件并直接显示到手机上

上一篇:android error: failed linking file resources.


下一篇:安卓App自动升级