android - 下载后如何在android的pdf查看器中显示并读取文件

标签 android

我创建了一个应用程序,如果用户单击任何 PDF,它将下载该 PDF。现在我想在下载后显示该 PDF。我不知道如何在 onPostExecute 方法下载后显示该 pdf。文件的存储路径为Environment.getExternalStorageDirectory() + "/"+ "android"+ "/"+ "Data"+ "/"+ "foldername"+"/"+"Filename"

public class DownloadTask {
cutomealertbox cdd;
File apkStorage = null;
File outputFile = null;
private Context context;

private String downloadUrl = "", downloadFileName = "";
public DownloadTask(Context context, String downloadUrl) {
    this.context = context;

    this.downloadUrl = downloadUrl;
    downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/'), downloadUrl.length());
    Log.e(TAG, downloadFileName);
    cdd=new cutomealertbox((Activity) context);
    new DownloadingTask().execute();
}

private class DownloadingTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        cdd.show(); // cdd is alert box
    }

    @Override
    protected void onPostExecute(Void result) {
        try {
            if (outputFile != null) {
                cdd.dismiss();
            } else {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                    }
                }, 3000);

                Log.e(TAG, "Cannot load please try again");

            }
        } catch (Exception e) {
                Log.e(TAG, "Download Failed with Exception - " + e);

        }

最佳答案

使用下面的方法并将上下文和本地路径作为参数传递。

public static void openFile(Context context, String localPath) {
    // Create URI
    try {
        File file = new File(localPath);

        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // Check what kind of file you are trying to open, by comparing the url with extensions.
        // When the if condition is matched, plugin sets the correct intent (mime) type,
        // so Android knew what application to use to open the file
        if (file.toString().contains(".pdf")) {
            // PDF file
            intent.setDataAndType(uri, "application/pdf");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }


    } catch (Exception e) {
        e.printStackTrace();
    }
}

关于android - 下载后如何在android的pdf查看器中显示并读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51591406/

相关文章:

java - NoClassDefFoundError 与 Android 构建路径上的必需项目

java - 为重载的 Java 函数编写文档

java - 如何在android中设置多个闹钟,在这种情况下最后一个闹钟会覆盖之前的闹钟

android - 将 Android NumberPicker 限制为用于数字输入的数字键盘(不是字母键盘)

android - 无法在Android Studio中使用调试器运行Robolectric单元测试

java - 如何从 MainActivity 添加到 network_security_config

android - 新 fragment 布局未显示在屏幕上 android

java - 如何在Android中创建firebase后台服务?

android - 将 Parcelable Arraylist 发送到 fragment

android - HTTP Live Streaming 中的时间戳不连续问题