简体   繁体   English

意图不打开pdf文件

[英]Intent not opening pdf file

i found this answer https://stackoverflow.com/a/10689094/11520105 ,and i tried this code ,it pops up dialog to select pdfviewer and when i tap Adobe reader then it simply just launches adobe reader but doesn't launch pdf file我找到了这个答案https://stackoverflow.com/a/10689094/11520105 ,我尝试了这个代码,它弹出对话框来选择 pdfviewer,当我点击 Adob​​e reader 时它只是启动 adobe reader 但不启动 pdf文件

code snippet代码片段

pdflistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

               UploadPDF uploadPDF = list.get(position);
               String url = uploadPDF.getUrl();
               Log.i("url",url);
                Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
                intent.setType("application/pdf");
                PackageManager pm = getPackageManager();
                List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
                if (activities.size() > 0) {
                    startActivity(intent);
                } else {
                    // Do something else here. Maybe pop up a Dialog or Toast
                    Toast.makeText(ShowPdfActivity.this, "Can't open pdf", Toast.LENGTH_SHORT).show();
                }

logCat日志猫

2020-01-01 18:05:56.259 15148-15148/com.tarandeepsingh.inventory V/FA: onActivityCreated
2020-01-01 18:05:56.306 15148-15186/com.tarandeepsingh.inventory V/FA: Activity resumed, time: 2896415632
2020-01-01 18:05:56.320 15148-15186/com.tarandeepsingh.inventory D/FA: Logging event (FE): screen_view(_vs), Bundle[{ga_event_origin(_o)=auto, ga_previous_class(_pc)=MainActivity, ga_previous_id(_pi)=3485492302754114157, ga_screen_class(_sc)=ShowPdfActivity, ga_screen_id(_si)=3485492302754114159}]
2020-01-01 18:05:57.157 15148-15148/com.tarandeepsingh.inventory I/url: https://firebasestorage.googleapis.com/v0/b/inventory-b98d3.appspot.com/o/uploads%2F1577868311721.pdf?alt=media&token=e543f039-38bd-4881-bcff-48b533ff22bf
2020-01-01 18:05:57.165 15148-15148/com.tarandeepsingh.inventory I/Timeline: Timeline: Activity_launch_request time:644743239 intent:Intent { act=android.intent.action.VIEW typ=application/pdf }
2020-01-01 18:05:57.200 15148-15186/com.tarandeepsingh.inventory V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 889
2020-01-01 18:05:57.207 15148-15186/com.tarandeepsingh.inventory V/FA: Activity paused, time: 2896416520
2020-01-01 18:05:59.218 15148-15186/com.tarandeepsingh.inventory D/FA: Application going to the background
2020-01-01 18:05:59.235 15148-15186/com.tarandeepsingh.inventory D/FA: Logging event (FE): app_background(_ab), Bundle[{ga_event_origin(_o)

as you can see in logcat , i am getting url but unable to launch default/already installed pdf viewer正如您在 logcat 中看到的,我正在获取 url 但无法启动默认/已安装的 pdf 查看器

thanks谢谢

To handle your needs, you need to download the PDF and store it into the device storage, so you can use it as you want using their path.为了满足您的需求,您需要下载PDF并将其存储到设备存储中,以便您可以使用它们的路径随意使用它。

Here's a full example of how to download a PDF file and open it when the download is finished :以下是如何下载PDF文件并在下载完成后打开它的完整示例:

String PDF_URL = "https://perso.univ-rennes1.fr/pierre.nerzic/Android/poly.pdf";



@SuppressLint("StaticFieldLeak")
private class DownloadFile extends AsyncTask<String, Integer, String> {

    String savedFilePath = null;
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //To ignore the file URI exposure.
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

        progressDialog = new ProgressDialog(PickLocationActivity.this);
        progressDialog.setTitle("Downloading PDF");
        progressDialog.setMessage("Please wait (0%)");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... urlParams) {
        int count;
        String fileName = urlParams[1] + ".pdf";
        File storageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                        + "/PDF_FOLDER/");
        boolean success = true;
        if (!storageDir.exists()) {
            success = storageDir.mkdirs();
        }
        if (success) {
            File file = new File(storageDir, fileName);
            savedFilePath = file.getAbsolutePath();
            if (!file.exists()) {
                try {
                    URL url = new URL(urlParams[0]);
                    URLConnection conexion = url.openConnection();
                    conexion.connect();
                    int lenghtOfFile = conexion.getContentLength();
                    InputStream input = new BufferedInputStream(url.openStream());
                    OutputStream output = new FileOutputStream(file);
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        publishProgress((int) (total * 100 / lenghtOfFile));
                        output.write(data, 0, count);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return savedFilePath;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setMessage("Please wait (" + values[0] + "%)");
    }

    @Override
    protected void onPostExecute(String pdfPath) {
        super.onPostExecute(pdfPath);
        if (pdfPath != null && !pdfPath.isEmpty()) {
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                progressDialog.dismiss();
                Uri path = Uri.fromFile(pdfFile);
                Intent Go = new Intent(Intent.ACTION_VIEW);
                Go.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Go.setDataAndType(path, "application/pdf");
                Go.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(Go);
            }
        }
    }
}

call it like this : new DownloadFile().execute(PDF_URL, "PDF_NAME");像这样调用它: new DownloadFile().execute(PDF_URL, "PDF_NAME"); don't forget to add INTERNET , READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions on your AndroidManifest.xml不要忘记在AndroidManifest.xml上添加INTERNETREAD_EXTERNAL_STORAGEWRITE_EXTERNAL_STORAGE权限


Otherwise, you can use this library PdfViewPager and go to Remote PDF's from a URL , it's doing the same thing (downloading PDF file into your device storage first)否则,您可以使用此库PdfViewPager从 URL转到远程 PDF ,它正在做同样的事情(首先将 PDF 文件下载到您的设备存储中)

I need to download file to open it , i can't open it in inbuilt/default pdfviewer using uri我需要下载文件才能打开它,我无法使用 uri 在内置/默认 pdfviewer 中打开它

String url = "given";
 DownloadManager downloadmanager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                    request.setTitle(name);
                    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
                            DownloadManager.Request.NETWORK_MOBILE);
                   request.setAllowedOverRoaming(false);
                    request.setDescription("Downloading");
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,name);
                    request.setMimeType(".pdf");

                    id = downloadmanager.enqueue(request);

using downloadManager is better way, so i used it使用 downloadManager 是更好的方法,所以我使用了它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM