android:下载一个pdf文件并在之后打开

时间:2012-12-06 18:43:47

标签: android pdf android-download-manager

我正在尝试从互联网上下载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);

}

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

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

感谢。

1 个答案:

答案 0 :(得分: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();
    }
}

或者你可以在这里引用我的答案。

How to use Asynchronous task for download progress dialog in fragment?

它用于下载文件并显示进度diolog.Here我使用asynch task.Call上面的方法在asynt任务的onpost()方法。 希望它也能帮到你