最近天氣有點冷,吹牛逼以前,先熱個身O(∩_∩)O哈哈~,android
整理了以前寫的方法,從新修改了文件下載demo,新demo從服務器下載文件地址(以圖片和pdf文件爲例):稍後附上服務器
https://download.csdn.net/download/qq_35702985/11688476app
若是調用okhttp工具類下載服務器文件報錯ide
請按如下步驟檢查:函數
1.動態申請權限,同時AndroidManifest.xml的application中添加工具
android:usesCleartextTraffic="true"
2.下載文件函數(downFile)在線程中調用this
3.downFile的第二個參數文件路徑寫成相對路徑(Environment.getExternalStorageDirectory() + "/download/")url
相關代碼:.net
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) {
//下載異常進行相關提示操做
}
});
}
源碼地址: 稍後附上 https://download.csdn.net/download/qq_35702985/11643721