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;
}
}
};
}