admin 管理员组文章数量: 887021
实现起来,稍稍简单,无非就是先下载,然后再打开,记住一点:如果已经下载,就直接打开。具体代码如下:联网下载请更换自己项目中的
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(); } }
版权声明:本文标题:Android用浏览器打开pdf文件 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1728363558h1233944.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论