java - 下载 PDF 不起作用

标签 java android pdf

在我的应用程序中,我有一个可扩展 ListView ,当我单击特定的子项时,我想打开从互联网下载的 PDF。问题是 pdf 文件 (Read.pdf) 始终为空,这意味着下载无法正常工作。

下载器类:

public class Downloader {

public static void DownloadFile(String fileURL, File directory) {
    try {

        FileOutputStream f = new FileOutputStream(directory);
        URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

部分 Activity :

private void registerClick() {
    expListView.setOnChildClickListener(new OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                                    int groupPosition, int childPosition, long id) {
            if ((groupPosition == 0) && (childPosition == 0)){
                File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE", "Read.pdf");
                try {
                    file.createNewFile();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                Downloader.DownloadFile("https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf", file);


                AbrirPDF.showPdf();
            }   else {

            }

            return false;
        }
    });

}

我认为 OpenPDF (AbrirPDF) 没有任何问题,但我会发布它...

public class AbrirPDF {



public static void showPdf()
{



    File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE/Read.pdf");
    PackageManager packageManager = ContextGetter.getAppContext().getPackageManager();
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    testIntent.setType("application/pdf");
    List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(file);
    intent.setDataAndType(uri, "application/pdf");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    ContextGetter.getAppContext().startActivity(intent);
}
}

谢谢。

最佳答案

理想情况下,您的下载应该在单独的线程中进行,以避免锁定您的应用。

这是一个还包含进度条的示例。

public class MainActivity extends Activity {

    private ProgressDialog pDialog;
    public static final int progress_bar_type = 0;

    private static String file_url = "https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        new DownloadFileFromURL().execute(file_url);

    }


    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type: // we set this to 0
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }

    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = conection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);

                // Output stream
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory().toString()
                        + "/2011.kml");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

        }

    }
}

关于java - 下载 PDF 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35092230/

相关文章:

java - 限制 JVM 使用的线程数

java - 为什么 deleteSurroundingText 不适用于表情符号并全选?

Android 2.2 + SQLite + 定义参照完整性约束

android - 动态按钮文本?

javascript - 从 AJAX 下载 PDF 文件成功回调

c# - 通过 Migradoc 在 pdf 中添加文档链接

java - 使用NamedParameterJdbcTemplate以一定批量大小批量更新

java - 每周处理 S3 中的所有文件

android - 将 ArrayList<CustomObject> 传递给另一个 Activity ,得到 NullPointerException

javascript - 在新选项卡中打开 PDF,保存文件时给出错误的文件名