android+加载pdf地址,Android 如何本地加载pdf文件(示例代码)

public classDownLoadPDF {private staticContext context;private staticFile file ;private static CustomDialog builder = null;private staticHandler ddhandle;private static DownLoadPDF instance = null;public staticDownLoadPDF getInstance(){if(instance==null){

synchronized (DownLoadPDF.class){if(instance==null){

instance= newDownLoadPDF();

}

}

}returninstance;

}public voiddownLoadPDF(final Context con, final String url, final String title, final Handler ddhandler) {

ddhandle=ddhandler;

context=con;

builder= newCustomDialog(con);

LayoutInflater inflater=(LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View view= inflater.inflate(R.layout.dialog_pdf_progress_new, null);

builder.setContentView(view);

builder.show();newThread() {

@Overridepublic voidrun() {try{

file=getFileFromServer(url,title);

sleep(200);if (file != null) {

handler.sendEmptyMessage(2);

}

}catch(Exception e) {

e.printStackTrace();

builder.dismiss();

handler.sendEmptyMessage(-1);

}

}

}.start();

}public voidcloseDilaoig(){if (builder != null&&builder.isShowing()) {

builder.dismiss();

}

}public static intlength ;public staticFile getFileFromServer(String path,String title)

throws Exception {//如果相等的话表示当前的sdcard挂载在手机上并且是可用的

if(Environment.getExternalStorageState().equals(

Environment.MEDIA_MOUNTED)) {

URL url= newURL(path);

HttpURLConnection conn=(HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5000);

conn.setDoInput(true);

conn.connect();

length=conn.getContentLength();

InputStreamis =conn.getInputStream();//将pdf文件存储在指定文件夹下

File filePath = new File(//指定文件夹路径);if (!filePath.exists()){

filePath.mkdir();

}

File file= new File(filePath , title+".pdf");

FileOutputStream fos= newFileOutputStream(file);

BufferedInputStream bis= new BufferedInputStream(is);byte[] buffer = new byte[1024];intlen;while ((len = bis.read(buffer)) != -1) {

fos.write(buffer,0, len);

handler.sendEmptyMessage(0);

}

fos.close();

bis.close();is.close();returnfile;

}else{

handler.sendEmptyMessage(-1);return null;

}

}private static Handler handler = newHandler(){

@Overridepublic voidhandleMessage(Message msg) {

super.handleMessage(msg);switch(msg.what) {case 0:break;case -1://下载失败

Toast.makeText(context, "下载失败,请稍后再试!", Toast.LENGTH_SHORT).show();break;case 2:

ddhandle.sendEmptyMessage(100);break;default:break;

}

}

};

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值