您的位置:首页 > 移动开发 > Android开发

Android下载并打开PDF文件

2017-07-06 16:27 525 查看

1.下载PDF文件到本地

private void downFile(){
String urlString = "http://14.215.72.79/file3.data.weipan.cn/61710973/8e6cfb727a439608032a222755e9c8e366cfb252?ip=1499330937,183.14.31.194&ssig=gpMUwXAXDI&Expires=1499331537&KID=sae,l30zoo1wmz&fn=%E6%9D%83%E5%A8%81%E6%95%B0%E7%8B%AC%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A.pdf&skiprd=2&se_ip_debug=183.14.31.194&corp=2&from=1221134&wsiphost=local";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
//实现连接
connection.connect();

if (connection.getResponseCode() == 200) {
InputStream is = connection.getInputStream();
//以下为下载操作
byte[] arr = new byte[1];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
int n = is.read(arr);
while (n > 0) {
bos.write(arr);
n = is.read(arr);
}
bos.close();
String path = Environment.getExternalStorageDirectory()
+ "/download/";
String[] name = urlString.split("/");
path = path + name[name.length - 1];
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.close();
//关闭网络连接
connection.disconnect();
Log.d("下载完成","下载完成");
openPDF(file);//打开PDF文件
}
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}

2.打开PDF文件

private void openPDF(File file) {
if (file.exists()) {
Log.d("打开","打开");
Uri path1 = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path1, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

try {
startActivity(intent);
}
catch (Exception e) {
Log.d("打开失败","打开失败");
}
}
}

3.新建一个线程调用下载方法

findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

new Thread(){
@Override
public void run() {
super.run();
downFile();
}
}.start();
}
});



注意:有些手机可能默认了文件的打开方式为WPS,WPS软件有时候是不能打开PDF文件的,这时就会出现一闪而过的情况

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: