簡體   English   中英

打算在Android N中打開PDF文件

[英]Intent to open PDF file in Android N

我一直試圖使用意圖打開PDF文件。 它對Adroid N之前的設備運行良好。以下是我使用的代碼

File file = new File(gridItems.get(position).getPath());
                        Intent intent = null;
                        if (Build.VERSION.SDK_INT < 24) {
                            intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.fromFile(file), "application/pdf");
                            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                        } else {
                            intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            Uri pdfURI = FileProvider.getUriForFile(GalleryPdfActivity.this, getApplicationContext()
                                    .getPackageName
                                            () +
                                    ".provider", file);
                            intent.putExtra(Intent.EXTRA_STREAM, pdfURI);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                            intent.setType("application/pdf");
                        }
                        try {
                            if (intent.resolveActivity(getPackageManager()) != null)
                                startActivity(intent);
                            else
                                AppUtils.toast("No Application found to open the pdf", GalleryPdfActivity.this);
                        } catch (Exception e) {
                            AppUtils.toast(e.getMessage(), GalleryPdfActivity.this);
                        }

文件選擇器打開,我選擇了Google PDF Viewer打開該應用程序。 但是返回錯誤“無法顯示PDF(未接收到文件)”。 我能夠在Android N之前的設備中打開相同的文件

FileProvider案例的Intent上添加FLAG_GRANT_READ_URI_PERMISSION 否則,其他應用將無法訪問內容。 請參閱文檔

添加FLAG_GRANT_READ_URI_PERMISSION

Intent intent = new Intent(Intent.ACTION_VIEW)
Uri outputFileUri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", file); 
intent.setDataAndType(outputFileUri, "application/pdf"); 
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
Intent in = Intent.createChooser(intent, "Open File");
startActivity(in);

還需要在res-> xml文件夾中添加provider_paths.xml,並需要在清單中添加以下代碼

<application>
   <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true"
            tools:replace="android:authorities">
            <meta-data
                tools:replace="android:resource"
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
 </application>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM