Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/191.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从android应用程序打开PDF_Java_Android_Pdf - Fatal编程技术网

Java 从android应用程序打开PDF

Java 从android应用程序打开PDF,java,android,pdf,Java,Android,Pdf,我使用自定义类从android应用程序中打开PDF。它检查PDF是否已经下载,然后使用现有的PDF查看器应用程序打开PDF。如果没有pdf查看器应用程序,那么它会尝试使用谷歌文档打开pdf 在Android Studio 2.2.3升级到2.3.2和构建工具版本从24版升级到25版之前,该课程一直运转良好。目标SDK仍然是API 24。无法找出问题的确切根本原因 PDF类: public class PDFTools { private static final String GOOGLE_DR

我使用自定义类从android应用程序中打开PDF。它检查PDF是否已经下载,然后使用现有的PDF查看器应用程序打开PDF。如果没有pdf查看器应用程序,那么它会尝试使用谷歌文档打开pdf

在Android Studio 2.2.3升级到2.3.2和构建工具版本从24版升级到25版之前,该课程一直运转良好。目标SDK仍然是API 24。无法找出问题的确切根本原因

PDF类

public class PDFTools {
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://docs.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";

/**
 * If a PDF reader is installed, download the PDF file and open it in a reader.
 * Otherwise ask the user if he/she wants to view it in the Google Drive online PDF reader.<br />
 * <br />
 * <b>BEWARE:</b> This method
 * @param context
 * @param pdfUrl
 * @return
 */
public static void showPDFUrl( final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}

/**
 * Downloads a PDF with the Android DownloadManager and opens it with an installed PDF reader app.
 * @param context
 * @param pdfUrl
 */

public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filename );
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        Uri uri = null;
        File docPath = new File(context.getExternalFilesDir(null), "Download");
        File newFile = new File(docPath, filename);

        uri = FileProvider.getUriForFile( context, BuildConfig.APPLICATION_ID + ".provider", newFile );

        openPDF( context, uri);
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ),
            context.getString( R.string.message_please_wait ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    Uri uri = null;
                    try {
                        uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", tempFile );

                    }catch (IllegalArgumentException iae) {
                        iae.printStackTrace();
                    }
                    if (uri !=null) {
                        openPDF(context, uri);
                    }
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}

/**
 * Show a dialog asking the user if he wants to open the PDF through Google Drive
 * @param context
 * @param pdfUrl
 */
public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

/**
 * Launches a browser to view the PDF through Google Drive
 * @param context
 * @param pdfUrl
 */
public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}
/**
 * Open a local PDF file with an installed reader
 * @param context
 * @param localUri
 */
public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}
/**
 * Checks if any apps are installed that supports reading of PDF files.
 * @param context
 * @return
 */
public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "test.pdf" );
    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    try {
        i.setDataAndType( FileProvider.getUriForFile( context, BuildConfig.APPLICATION_ID + ".provider" ,tempFile ), PDF_MIME_TYPE );
    }catch (IllegalArgumentException iae ) {
    }
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}
公共类PDFTools{
私有静态最终字符串GOOGLE\u DRIVE\u PDF\u READER\u PREFIX=”http://docs.google.com/viewer?url=";
私有静态最终字符串PDF\u MIME\u TYPE=“application/PDF”;
私有静态最终字符串HTML\u MIME\u TYPE=“text/HTML”;
/**
*如果安装了PDF阅读器,请下载PDF文件并在阅读器中打开。
*否则,询问用户是否希望在Google Drive online PDF阅读器中查看该文档。
*
*注意:这种方法 *@param上下文 *@param pdfUrl *@返回 */ 公共静态void showPDFUrl(最终上下文,最终字符串pdfUrl){ 如果(isPDFSupported(上下文)){ 下载和OpenPDF(上下文,pdfUrl); }否则{ askToOpenPDFThroughGoogleDrive(上下文,pdfUrl); } } /** *使用Android DownloadManager下载PDF,并使用已安装的PDF阅读器应用程序打开。 *@param上下文 *@param pdfUrl */ 公共静态void downloadOpenPDF(最终上下文,最终字符串pdfUrl){ //获取文件名 最终字符串文件名=pdfUrl.substring(pdfUrl.lastIndexOf(“/”)+1); //下载的PDF文件将放置的位置 final File tempFile=新文件(context.getExternalFilesDir(Environment.DIRECTORY\u下载),文件名); if(tempFile.exists()){ //如果我们以前下载过该文件,请继续并显示它。 Uri=null; File docPath=新文件(context.getExternalFilesDir(null),“下载”); File newFile=新文件(docPath,文件名); uri=FileProvider.getUriForFile(上下文,BuildConfig.APPLICATION\u ID+“.provider”,newFile); openPDF(上下文,uri); 返回; } //下载时显示进度对话框 final ProgressDialog progress=ProgressDialog.show(context,context.getString(R.string.pdf\u show\u local\u progress\u title), getString(R.string.message\u please\u wait),true); //创建下载请求 DownloadManager.Request r=newdownloadmanager.Request(Uri.parse(pdfUrl)); r、 setDestinationNexternalFilesDir(上下文,Environment.DIRECTORY\u下载,文件名); final DownloadManager dm=(DownloadManager)context.getSystemService(context.DOWNLOAD_服务); BroadcastReceiver onComplete=新的BroadcastReceiver(){ @凌驾 公共void onReceive(上下文、意图){ 如果(!progress.isShowing()){ 返回; } 上下文。未注册接收者(本); 进步。解散(); long downloadId=intent.getLongExtra(DownloadManager.EXTRA\u DOWNLOAD\u ID,-1); 游标c=dm.query(new DownloadManager.query().setFilterById(downloadId)); if(c.moveToFirst()){ int status=c.getInt(c.getColumnIndex(DownloadManager.COLUMN_status)); 如果(状态==DownloadManager.status\u成功){ Uri=null; 试一试{ uri=FileProvider.getUriForFile(上下文,BuildConfig.APPLICATION_ID+“.provider”,tempFile); }捕获(IllegalArgumentException iae){ iae.printStackTrace(); } if(uri!=null){ openPDF(上下文,uri); } } } c、 close(); } }; registerReceiver(onComplete,新的IntentFilter(DownloadManager.ACTION\u DOWNLOAD\u COMPLETE)); //将请求排队 dm.enqueue(r); } /** *显示一个对话框,询问用户是否希望通过Google Drive打开PDF *@param上下文 *@param pdfUrl */ 通过GoogleDrive公开静态void asktoopenpdfthr(最终上下文,最终字符串pdfUrl){ 新建AlertDialog.Builder(上下文) .setTitle(R.string.pdf\u show\u online\u dialog\u title) .setMessage(R.string.pdf_show_online_dialog_question) .setNegativeButton(R.string.pdf_show_online_dialog_button_no,null) .setPositiveButton(R.string.pdf_show_online_dialog_button_yes,new DialogInterface.OnClickListener(){ @凌驾 public void onClick(DialogInterface dialog,int which){ openPDFThroughGoogleDrive(上下文,pdfUrl); } }) .show(); } /** *启动浏览器以通过Google Drive查看PDF *@param上下文 *@param pdfUrl */ 公共静态void openPDFThroughGoogleDrive(最终上下文,最终字符串pdfUrl){ 意向i=新意向(意向.行动\视图); i、 setDataAndType(Uri.parse(GOOGLE\u DRIVE\u PDF\u READER\u PREFIX+pdfUrl)、HTML\u MIME\u TYPE); 背景。起始触觉(i); } /** *打开带有已安装读卡器的本地PDF文件 *@param上下文 *@param localUri */ 公共静态最终void openPDF(上下文上下文,urilocaluri){ 意向i=新意向(意向.行动\视图); i、 setFlags(Intent.FLAG\u GRANT\u READ\u URI\u PERMISSION); i、 setDataAndType(localUri、PDF\u MIME\u类型); 背景。起始触觉(i); } /** *检查是否安装了支持读取PDF文件的应用程序。 *@param上下文 *@返回 */ 支持公共静态布尔值ISPDFS(上下文){ 意向i=新意向(意向.行动\视图); final File tempFile=新文件(context.getExternalFilesDir(Environment.DIRECTORY_下载),“test.pdf”); i、 addFlags(Intent.FLAG\u GRANT\u READ\u URI\u PERMI
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/<PACKAGE>/files/Download/javascript_pdf_version.pdf
public PdfByteArrayObject getPrintjob(String empId) {
    PdfByteArrayObject pdfByteArrayObject = null;
    try {
        getUrl();
        RestTemplate restTemplate = new RestTemplate();            
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        pdfByteArrayObject = restTemplate.getForObject("pdfURL" + empId, PdfByteArrayObject.class);


    } catch (Exception e) {
      e.printStackTrace();            
      Log.e("webser======", e.toString());
    }
    return pdfByteArrayObject;
}
public void getUrl() {
    StringBuffer stringBuffer = new StringBuffer();
    String aDataRow = "";
    String aBuffer = "";
    try {
        File serverPath = new File(Environment.getExternalStorageDirectory(), "ServerUrl");

        if (serverPath.exists()) {
            FileInputStream fIn = new FileInputStream(serverPath);
            BufferedReader myReader = new BufferedReader(
                    new InputStreamReader(fIn));

            while ((aDataRow = myReader.readLine()) != null) {
                aBuffer += aDataRow;
            }
            RestUrl = aBuffer;
            Log.e("RestUrl", RestUrl + "--");
            myReader.close();
        } else {
            Log.e("RestUrl", "File not found");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    // Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
}
public class PdfByteArrayObject {

private byte[] pdffile;

public byte[] getPdffile() {
    return pdffile;
}

public void setPdffile(byte[] pdffile) {
    this.pdffile = pdffile;
}
}