简体   繁体   中英

Android:How to open pdf?

I try to open pdf, but when I press the button, nothing happens. Where is my mistake?

OnClickListener oclBt2 = new OnClickListener(){
            public void onClick(View v) {
                File file = new File("http://testserv1.p.ht/1/ksu016.pdf");

                if (file.exists()) {
                Uri path = Uri.fromFile(file);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);   
                try {
                    startActivity(intent);
                    } 
                catch (ActivityNotFoundException e) {
                     e.printStackTrace();
                    }
                }
            }
        };

I corrected my code, but it doesn't work again :( when I press the button, appears the window (Sorry, but my reputation doesn't allow to post images)

OnClickListener oclBt2 = new OnClickListener(){
            public void onClick(View v) {
                Uri path = Uri.parse("http://testserv1.p.ht/1/ksu016.pdf");
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                try {
                startActivity(intent);
                } 
                catch (ActivityNotFoundException e) {               
                mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url=http://hostforandroid.elitno.net/pdf-test.pdf" );
                setContentView(mWebView);
                }               
            }
        };

First, File is for local files, not http URLs. Use Uri.parse("http://testserv1.p.ht/1/ksu016.pdf"); to get a Uri pointing to an http URL.

Second, there may be no PDF viewers that are set up to directly download from an HTTP URL. For greater compatibility, you can arrange to download the PDF first (using DownloadManager or your own HTTP client code), then view the local PDF file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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