实现起来,稍稍简单,无非就是先下载,然后再打开,记住一点:如果已经下载,就直接打开。具体代码如下:联网下载请更换自己项目中的
public class PdfHttpDownloader { private Context context; public PdfHttpDownloader(Context context) { this.context = context; } /** * 打开pdf * pdf:PDF url * name:pdf文件的名字 */ public void startPdfActivity(String pdf, String name) { String terPath = getSDPath() + "/trader/" + name + ".PDF"; File file = new File(terPath); if (file.exists()) { Intent intent = getPdfFileIntent(terPath); context.startActivity(intent); } else { downLoadPdf(pdf, name); } } public Intent getPdfFileIntent(String path) { Intent i = new Intent(Intent.ACTION_VIEW); i.addCategory(Intent.CATEGORY_DEFAULT); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri uri = Uri.fromFile(new File(path)); i.setDataAndType(uri, "application/pdf"); return i; } public void downLoadPdf(final String pdf, final String name) { Request request = new Request.Builder() .url(pdf) .get() .build(); OkHttpClient http = new OkHttpClient(); http.newCall(request) .enqueue(new com.squareup.okhttp.Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) { InputStream is = null; byte[] buf = new byte[1024]; int len = 0; FileOutputStream fos = null; String terPath = null; File file = null; try { is = response.body().byteStream(); terPath = getSDPath() + "/trader/" + name + ".PDF"; file = new File(terPath); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); //下载成功 if (file.exists()) { Intent intent = getPdfFileIntent(terPath); context.startActivity(intent); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } }); } private String getSDPath() { File sdDir = null; boolean sdCardExist = Environment.getExternalStorageState() .equals(Environment.MEDIA_MOUNTED); //判断sd卡是否存在 if (sdCardExist) { sdDir = Environment.getExternalStorageDirectory();//获取跟目录 } return sdDir.toString(); } }