Android下载PDF文件

版权声明:转载请注明出处 https://blog.csdn.net/l707941510/article/details/88956475

1.下载PDF文件到本地

 private void downFile(String urlString){
        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.新建一个线程调用下载方法

    private class MyAsyncTask extends AsyncTask<String, Void, File> {

        @Override
        protected File doInBackground(String... str) {
            return downFile(str[0]);//开始下载
        }

        @Override
        protected void onPostExecute(final File file) {
            //下载完成,修改UI
        }
    }

4.调用


String url = "https://staticzcjb.weibangong.com/pdf/business_license.pdf";
new MyAsyncTask().execute(url, null, null);

猜你喜欢

转载自blog.csdn.net/l707941510/article/details/88956475