Android download pdf file
Hello everyone, Hello everyone, I have recently come into contact with the pdf download function. I checked a lot on the Internet, but many of them are not applicable. In the end, the hard work paid off, hahaha, it was successful. Without further ado, take a look below.
1. First, you need to create a tool class, as follows:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class DownloadUtilNew {
private static DownloadUtilNew downloadUtil;
private final OkHttpClient okHttpClient;
public static DownloadUtilNew get() {
if (downloadUtil == null) {
downloadUtil = new DownloadUtilNew();
}
return downloadUtil;
}
private DownloadUtilNew() {
okHttpClient = new OkHttpClient();
}
/**
* @param url 下载连接
* @param destFileDir 下载的文件储存目录
* @param destFileName 下载文件名称
* @param listener 下载监听
*/
public void download(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) {
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 下载失败监听回调
listener.onDownloadFailed(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
// 储存下载文件的目录
File dir = new File(destFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, destFileName);
try {
is = response.body().byteStream();
long total = response.body().contentLength();
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
// 下载中更新进度条
listener.onDownloading(progress);
}
fos.flush();
// 下载完成
listener.onDownloadSuccess(file);
} catch (Exception e) {
listener.onDownloadFailed(e);
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
}
});
}
public interface OnDownloadListener {
/**
* @param file 下载成功后的文件
*/
void onDownloadSuccess(File file);
/**
* @param progress 下载进度
*/
void onDownloading(int progress);
/**
* @param e 下载异常信息
*/
void onDownloadFailed(Exception e);
}
2. Then start the call in the second step, as follows:
btn_downLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String time= CommonNew.getCurrentTime();
downFile(time+"nb", mPdfUrl);
}
});
/**
* 下載文件
*
* @param name
* @param urlString
*/
public void downFile(String name, String urlString) {
Log.d("info","存储的文件名是=="+name+".pdf");
DownloadUtilNew.get().download(urlString, Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "NBFile", name + ".pdf", new DownloadUtilNew.OnDownloadListener() {
@Override
public void onDownloadSuccess(File file) {
Log.v("info", "下载成功,文件已存入手机内部存储设备根目录下NBFile文件夾中");
runOnUiThread(new Runnable() {
@Override
public void run() {
XToast.showShort(mContext,"下载成功,文件已存入手机内部存储设备根目录下NBFile文件夾中");
}
});
Looper.prepare();//增加部分
Looper.loop();//增加部分
}
@Override
public void onDownloading(int progress) {
Log.v("info", "下载進度" + progress);
// progressDialog.setProgress(progress);
}
@Override
public void onDownloadFailed(Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
XToast.showShort(mContext,"下载失败,请重试");
}
});
Log.d("info","下载失败了 "+e.toString());
// if (progressDialog != null && progressDialog.isShowing()) {
// progressDialog.dismiss();
// }
}
});
}
3. In the third step, you need to add permissions:
int permission = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// 请求权限
ActivityCompat.requestPermissions(this, new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_REQ_CODE);
}
As for the write permissions for those files in AndroidManifest. Create the file with the permissions, but it still failed. I checked the reason and it said it was partitioned storage. Search it by yourself, as shown below: Yes, yes, you need to
add the code circled in red.
OK, that's probably it,