3

我正在尝试从 Internet 下载 pdf 文档,然后,当下载结束时,通过包自动打开它。

我找到了一些通过 DownloadManager 下载的解决方案,但之后没有打开它的答案。我测试过的代码之一是:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                long downloadId = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                Query query = new Query();
                query.setFilterById(enqueue);
                Cursor c = dm.query(query);
                if (c.moveToFirst()) {
                    int columnIndex = c
                            .getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c
                            .getInt(columnIndex)) {

                        String uriString = c
                                .getString(c
                                        .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        Uri uri = Uri.parse(uriString);

                        intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);

                        intent.setDataAndType(uri, "application/pdf");
                        startActivity(intent);



                    }
                }
            }
        }
    };

    registerReceiver(receiver, new IntentFilter(
            DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

public void onClick(View view) {
    dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    Request request = new Request(
            Uri.parse("http://www.xxxxxxx.org/directory/abc.pdf"));
    enqueue = dm.enqueue(request);

}

但是当下载成功结束时,包找不到文件。

我需要你的帮助。我花了两周时间通过谷歌和安卓书籍寻找解决方案,但没有成功。

谢谢。

4

1 回答 1

0

创建此方法并在您的代码中调用它

public void showPdf() {
    try {
        File file = new File(Environment.getExternalStorageDirectory()
                + "/Download/" + name + "CV.pdf");//name here is the name of any string you want to pass to the method
        if (!file.isDirectory())
            file.mkdir();
        Intent testIntent = new Intent("com.adobe.reader");
        testIntent.setType("application/pdf");
        testIntent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        testIntent.setDataAndType(uri, "application/pdf");
        startActivity(testIntent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

或者你可以在这里参考我的答案。

如何在片段中使用异步任务进行下载进度对话框?

它用于下载文件和显示进度对话框。这里我使用了异步任务。在异步任务的 onpost() 方法中调用上述方法。希望对你也有帮助

于 2016-11-04T10:29:19.270 回答