Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/209.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 intent从服务器打开pdf文件_Java_Android_Pdf_Android Intent - Fatal编程技术网

Java 使用android intent从服务器打开pdf文件

Java 使用android intent从服务器打开pdf文件,java,android,pdf,android-intent,Java,Android,Pdf,Android Intent,我正在网上搜索如何使用android上的默认pdf查看器从服务器打开pdf文件。我发现的是先下载文件,然后在intent中启动它,或者用googledocs加载它。我不想做这些。我只想直接从手机的默认pdf查看器中的服务器加载它。我试着打开视频网址的意图,它的工作。但故意打开pdf url是行不通的。下面是我的代码 private void openFilePDF(){ try{ Toast.makeText(getBaseContext(), "Open

我正在网上搜索如何使用android上的默认pdf查看器从服务器打开pdf文件。我发现的是先下载文件,然后在intent中启动它,或者用googledocs加载它。我不想做这些。我只想直接从手机的默认pdf查看器中的服务器加载它。我试着打开视频网址的意图,它的工作。但故意打开pdf url是行不通的。下面是我的代码

private void openFilePDF(){
        try{
            Toast.makeText(getBaseContext(), "Opening PDF... ", Toast.LENGTH_SHORT).show();
            Intent inte = new Intent(Intent.ACTION_VIEW);
            inte.setDataAndType(
                    Uri.parse("http://122.248.233.68/pvfiles/Guide-2.pdf"),
                    "application/pdf");

            startActivity(inte);
            }catch(ActivityNotFoundException e){
                Log.e("Viewer not installed on your device.", e.getMessage());
            }
    }

有什么方法可以加载pdf url吗?

首先创建一个downloader类

public class Downloader {

    public static void DownloadFile(String fileURL, File directory) {
        try {

            FileOutputStream f = new FileOutputStream(directory);
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {
                f.write(buffer, 0, len1);
            }
            f.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
然后创建一个从internet下载PDF文件的活动

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String extStorageDirectory = Environment.getExternalStorageDirectory()
        .toString();
        File folder = new File(extStorageDirectory, "pdf");
        folder.mkdir();
        File file = new File(folder, "Read.pdf");
        try {
            file.createNewFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Downloader.DownloadFile("http://122.248.233.68/pvfiles/Guide-2.pdf", file);

        showPdf();
    }
    public void showPdf()
        {
            File file = new File(Environment.getExternalStorageDirectory()+"/Mypdf/Read.pdf");
            PackageManager packageManager = getPackageManager();
            Intent testIntent = new Intent(Intent.ACTION_VIEW);
            testIntent.setType("application/pdf");
            List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/pdf");
            startActivity(intent);
        }
}
最后在
AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

您可以使用WebView尝试此操作:

public class MyPdfViewActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WebView mWebView=new WebView(MyPdfViewActivity.this);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setPluginsEnabled(true);
    mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo);
    setContentView(mWebView);
  }
}

据我说,没有办法直接在设备上打开您的PDF文件。由于android设备的浏览器属性,当我们试图打开PDF文件时,它会下载到设备上。只有两种方法可以打开PDF文件

  • 您可以使用PDF应用程序意图选择用于打开文件的应用程序

  • 您可以将文件的服务器url附加到Google docs url,并可以在浏览器中打开它,以便在浏览器中打开您的PDF文件


  • 从服务器下载Pdf文件,下载完成后,您可以使用挂起的意图打开此Pdf文件。

    在进入代码之前,只需查看下图,其中显示了我的附加代码的功能

    步骤-1:您需要在异步任务上创建一个url,以便从服务器url下载文件。 见以下代码:

    public class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
    
    private NotificationManager mNotifyManager;
    private NotificationCompat.Builder build;
    private File fileurl;
    int id = 123;
    OutputStream output;
    private Context context;
    private String selectedDate;
    private String ts = "";
    
    public DownloadFileFromURL(Context context, String selectedDate) {
        this.context = context;
        this.selectedDate = selectedDate;
    
    }
    
    protected void onPreExecute() {
        super.onPreExecute();
    
        mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        build = new NotificationCompat.Builder(context);
        build.setContentTitle("Download")
                .setContentText("Download in progress")
                .setChannelId(id + "")
                .setAutoCancel(false)
                .setDefaults(0)
                .setSmallIcon(R.drawable.ic_menu_download);
    
        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(id + "",
                    "Social Media Downloader",
                    NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("no sound");
            channel.setSound(null, null);
            channel.enableLights(false);
            channel.setLightColor(Color.BLUE);
            channel.enableVibration(false);
            mNotifyManager.createNotificationChannel(channel);
    
        }
        build.setProgress(100, 0, false);
        mNotifyManager.notify(id, build.build());
        String msg = "Download started";
        //CustomToast.showToast(context,msg);
    }
    
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        ts = selectedDate.split("T")[0];
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            int lenghtOfFile = conection.getContentLength();
    
            InputStream input = new BufferedInputStream(url.openStream(),
                    8192);
            // Output stream
            output = new FileOutputStream(Environment
                    .getExternalStorageDirectory().toString()
                    + Const.DownloadPath + ts + ".pdf");
            fileurl = new File(Environment.getExternalStorageDirectory()
                    + Const.DownloadPath + ts + ".pdf");
            byte[] data = new byte[1024];
    
            long total = 0;
    
            while ((count = input.read(data)) != -1) {
                total += count;
                int cur = (int) ((total * 100) / lenghtOfFile);
    
                publishProgress(Math.min(cur, 100));
                if (Math.min(cur, 100) > 98) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        Log.d("Failure", "sleeping failure");
                    }
                }
                Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "\n " + cur);
    
                output.write(data, 0, count);
            }
    
            output.flush();
    
            output.close();
            input.close();
    
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
    
        return null;
    }
    
    protected void onProgressUpdate(Integer... progress) {
        build.setProgress(100, progress[0], false);
        mNotifyManager.notify(id, build.build());
        super.onProgressUpdate(progress);
    }
    
    @Override
    protected void onPostExecute(String file_url) {
        build.setContentText("Download complete");
        Intent intent = new Intent(context, DownloadBroadcastReceiver.class);
        Uri finalurl = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", fileurl);
        intent.putExtra("currenturl", finalurl.toString());
        intent.putExtra("selectedfilename", ts);
        context.sendBroadcast(intent);
        build.setProgress(0, 0, false);
        mNotifyManager.notify(id, build.build());
    } }
    
    此处创建了GrantAllpermission方法,通过该方法支持所有设备

     private void grantAllUriPermissions(Context context, Intent downloadintent, Uri finalurl) {
        List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(downloadintent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            context.grantUriPermission(packageName, finalurl, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    }
    
    在requestLegacyExternalStorage的帮助下,您可以轻松获得下载文件的列表

    步骤-5:现在最后一步是在点击事件中调用异步类文件。在这里我写的pdf图像点击代码。要调用异步任务,请使用下面的代码

     <receiver android:name=".services.DownloadBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    
     new DownloadFileFromURL(fContext,selectedDate).execute(currentResponse.getData());
    
    您可以从以下链接下载以上代码和整个文件:


    我不想下载,只想从服务器加载。请参阅此链接以获取参考tom下载文件谢谢您的回复。但是pdf应用程序只能打开本地文件。它无法从服务器加载文件。是的,您必须将文件下载到设备,然后您可以使用intent打开特定文件。谢谢您的信息。我试试。@ksh你的问题解决了吗?有没有什么答案对你有帮助?试试看@AnandPrakash@GrlsHu还有一件事,兄弟,你能推荐一些api用于在Android(4.4之前)上从一组数据生成pdf吗?@AnandPrakash如果没有任何pdf应用程序,那么它将无法工作。As
    Intent
    将找不到任何与pdf文件相关的应用程序。另一种方法是您也可以直接在浏览器中显示pdf。如果您不想在浏览器中加载,那么您必须为pdfviewer使用第三方api。我知道这确实很旧,但为了完整性,
    setPluginsEnabled()
    在api级别9中被弃用,在api级别18中被删除。较新的版本
    setPluginState(WebSettings.PluginState.ON)
    在API级别8中添加,但在API级别18中不推荐使用。API级别18以上不支持插件。@LeeRichardson谢谢你的评论。你能用同样的方法更新答案吗。这一点最重要的是,用“”点击可下载的PDF文件URL绑定。。
     <receiver android:name=".services.DownloadBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    
      <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_provider_path" />
        </provider>
    
    android:requestLegacyExternalStorage="true"
    
     new DownloadFileFromURL(fContext,selectedDate).execute(currentResponse.getData());