通过android意图打开在线pdf文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23240469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:56:16  来源:igfitidea点击:

Open online pdf file through android intent?

androidpdfandroid-intent

提问by user3538235

Currently I have a pdf url, and I would like to simply using the intent to open it, however, it does not work if I put the urlin intent

目前,我有一个PDF url,我想简单地使用意向来打开它,但是,这是行不通的,如果我把urlintent

My code is like this, it always throw ActivityNotFoundExceptionerror

我的代码是这样的,总是 ActivityNotFoundException报错

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(law.url), "application/pdf");

try {
    startActivity(intent);
} catch (ActivityNotFoundException e){
    Utility.showErrorDialog(
        ctx,ctx.getResources().getString(R.string.sys_in, 
        ctx.getResources().getString(R.string.err_no_pdf_reader), 
        ctx.getResources().getString(R.string.close));
}

Also I tried the goolge doc approach but my client reject this, so I am not using this method

我也尝试了 goolge doc 方法,但我的客户拒绝了,所以我没有使用这种方法

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setDataAndType(Uri.parse("http://docs.google.com/viewer?url=" 
+ publish.get(Integer.parseInt((String) view.getTag())).pdfURL), "text/html");  
ctx.startActivity(intent);

Thanks for help

感谢帮助

Log cat error Update

记录猫错误更新

04-23 18:18:50.487: E/AndroidRuntime(17161): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=http://oshc.zizsoft.com/oshc_testing.pdf typ=application/pdf }
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1568)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1439)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.app.Activity.startActivityForResult(Activity.java:3356)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.app.Activity.startActivityForResult(Activity.java:3317)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:848)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.support.v4.app.Fragment.startActivity(Fragment.java:878)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at com.example.oshpedia.Fragment.Shelf.onItemClick(Shelf.java:142)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at it.sephiroth.android.library.widget.AdapterView.performItemClick(AdapterView.java:299)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at it.sephiroth.android.library.widget.AbsHListView.performItemClick(AbsHListView.java:972)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at it.sephiroth.android.library.widget.AbsHListView$PerformClick.run(AbsHListView.java:2511)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at it.sephiroth.android.library.widget.AbsHListView.run(AbsHListView.java:3200)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.os.Handler.handleCallback(Handler.java:615)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.os.Looper.loop(Looper.java:137)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.app.ActivityThread.main(ActivityThread.java:4882)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at java.lang.reflect.Method.invokeNative(Native Method)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at java.lang.reflect.Method.invoke(Method.java:511)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at dalvik.system.NativeStart.main(Native Method)

回答by Akanksha Hegde

You can view or download the pdf by either of the two ways i.e by opening it in device in-built browser or in the webview by embedding it in your app.

您可以通过两种方式之一查看或下载 pdf,即通过在设备内置浏览器中打开它或通过将其嵌入您的应用程序在 webview 中打开它。

To open the pdf in browser,

要在浏览器中打开 pdf,

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);

Instead to open in webview,

而不是在 webview 中打开,

 Webview webView = (WebView) findViewById(R.id.webView1);
 webView.getSettings().setJavaScriptEnabled(true);
 webView.loadUrl(pdf_url);

回答by Alexander Skvortsov

Best practice is wrapping your Intentto Chooserbefore starting. It provides users with built-in application selection dialog and lets avoid ActivityNotFoundException

最好的做法是你的包裹IntentChooser在开始之前。它为用户提供了内置的应用程序选择对话框,让我们避免ActivityNotFoundException

Here a little example:

这里有一个小例子:

Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setDataAndType(Uri.parse(msg.getData()), Constants.MIME_PDF);

Intent chooser = Intent.createChooser(browserIntent, getString(R.string.chooser_title));
chooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // optional

startActivity(chooser);

Where Constants.MIME_PDFis defined as String value "application/pdf".

其中Constants.MIME_PDF定义为字符串值“application/pdf”。



It is possible to ask PackageManageris this Intenthas appropriate handling Activityor not.

可以问PackageManagerIntent是否有适当的处理Activity

public static boolean isActivityForIntentAvailable(Context context, Intent intent) {
    final PackageManager packageManager = context.getPackageManager();
    List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

回答by Asad Butt

you can view PDF in web view like this

您可以像这样在网络视图中查看 PDF

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setDataAndType(Uri.parse( "http://docs.google.com/viewer?url=" + pdfLink), "text/html");

startActivity(intent);

回答by Mahendra

you can view pdf in webview like this

您可以像这样在 webview 中查看 pdf

WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginsEnabled(true);
webView.loadUrl("https://docs.google.com/viewer?"+pdf_url);

回答by Deepshikha Puri

Download source code from here (Open Pdf from url in Android Programmatically)

从这里下载源代码(从 Android 中的 url 以编程方式打开 Pdf

MainActivity.java

主活动.java

package com.deepshikha.openpdf;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView)findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
        webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

        webview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url){
                // do your stuff here
                progressbar.setVisibility(View.GONE);
            }
        });

    }
}

回答by Jorgesys

I see that you are trying this method defining the data type:

我看到您正在尝试使用此方法定义数据类型:

Intent intent = new Intent();
intent.setDataAndType(Uri.parse(url), "application/pdf");
startActivity(intent);

but it will cause:

但它会导致:

ActivityNotFoundException: No Activity found to handle Intent

ActivityNotFoundException:没有找到处理意图的活动

Use method without the type definition and it will work perfectly:

使用没有类型定义的方法,它将完美地工作:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);

回答by shkschneider

The actual error

实际错误

android.content.ActivityNotFoundException: No Activity found to 
handle Intent 
{
 act=android.intent.action.VIEW 
 dat=http://oshc.zizsoft.com/oshc_testing.pdf typ=application/pdf 
}

This says that:

这说:

  1. You "broadcast" and Intent to let the system try to open a PDFfile
  2. The system does not find any application registered to be able to handle this type of file (PDF)
  1. 你 " broadcast" 和 Intent 让系统尝试打开一个PDF文件
  2. 系统未找到任何已注册的应用程序可以处理此类文件 ( PDF)

You just need a PDF viewerof some kind.

你只需要PDF viewer一种。

Solution

解决方案

Get a PDF readerapp or use @Mahendra's solution.

获取PDF reader应用程序或使用@Mahendra 的解决方案。

回答by Dinesh Sarma

you can try this. it works for both .pdfand .docx

你可以试试这个。它适用于.pdf.docx

 String pdfUrl = "abc.pdf"; //
 String url = "http://docs.google.com/gview?embedded=true&url=" + pdfUrl;

 WebView webView = findViewById(R.id.webview_cv_viewer);
 webView.getSettings().setSupportZoom(true);
 webView.getSettings().setJavaScriptEnabled(true);
 webView.loadUrl(url);

回答by Aziz

With kotlin using anko, simply call

使用 kotlin 使用anko,只需调用

 context.browse(PDF_URL)

to open any doc file, your browser will redirect you to the doc viewer app.

要打开任何文档文件,您的浏览器会将您重定向到文档查看器应用程序。

If you want to use Google Docs, then append your pdf url as,

如果您想使用Google Docs,请将您的 pdf 网址附加为,

"http://docs.google.com/viewer?url=$PDF_URL"

回答by Be Champzz

If you use Intent you will be directed to browser all the Time so Use PDFView Android Widget to View Pdf With in an Android application Assuming that you already have PDF Urlor You can Pass the URL to this activity using Intent

如果您使用 Intent,您将一直被定向到浏览器,因此使用 PDFView Android Widget 在 Android 应用程序中查看 Pdf 假设您已经拥有 PDF Url,或者您可以使用 Intent 将 URL 传递给此活动

Step 1 : Add Dependencies

第 1 步:添加依赖项

implementation 'com.github.barteksc:android-pdf-viewer:3.1.0-beta.1'
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

Sync the Gradle

同步 Gradle

Step 2 : Create a Layout [Text View is Optional]

第 2 步:创建布局 [文本视图是可选的]

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ViewPdf">




    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/ViewPdf"
        android:layout_height="match_parent"
        android:layout_width="match_parent"

        />

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"
        />
</RelativeLayout>

Step 3 : Here is the Activity.java files code , Add URL to pdfUrlvariable in middle of the code

第 3 步:这是 Activity.java 文件代码,将 URL 添加到代码中间的pdfUrl变量

package com.example.firebase;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.barteksc.pdfviewer.PDFView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ViewPdf extends AppCompatActivity {

    private TextView txt; // You can remove if you don't want this
    private PDFView pdf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pdf);
        pdf = findViewById(R.id.ViewPdf);
        txt = findViewById(R.id.txt);

        //Intent inten = getIntent();
        String pdfUrl = "Add PDF url"
        //Toast.makeText(this, pdfUrl, Toast.LENGTH_SHORT).show();


        try{
            new RetrievePdfStream().execute(pdfUrl);
        }
        catch (Exception e){
            Toast.makeText(this, "Failed to load Url :" + e.toString(), Toast.LENGTH_SHORT).show();
        }
    }


class RetrievePdfStream extends AsyncTask<String, Void, InputStream>{
    @Override
    protected InputStream doInBackground(String... strings) {
        InputStream inputStream = null;

        try {
            URL url = new URL(strings[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            if (urlConnection.getResponseCode() == 200) {
                inputStream = new BufferedInputStream(urlConnection.getInputStream());

            }
        } catch (IOException e) {
            return null;

        }
        return inputStream;
    }
        @Override
        protected void onPostExecute(InputStream inputStream) {
            pdf.fromStream(inputStream).load();
        }
    }
}

STEP 4 : Don't Forget to change / Give the pdf url in above code to make it work

第 4 步:不要忘记更改/在上面的代码中提供 pdf url 以使其工作