如何直接从app chooser中的URL打开PDF文件

时间:2016-10-06 13:51:51

标签: android pdf android-intent

我需要打开一个PDF文件,我从JSON的URL中获取。

此网址在网址末尾不包含文件扩展名。我试过这样的事情:

        final String pdfUrl = dataUrl.replace("data", "file") + "/x?filefield=" + tf.getFieldName() + "&context=\"" + dataItemIdModOne + "\"&skipcache=1";
        SharedPreferences sharedPrefs = getActivity().getSharedPreferences(Constants.userDetails, MODE_PRIVATE);
        String username = sharedPrefs.getString(Constants.user, "");
        String password = sharedPrefs.getString(Constants.pass, "");
        String userPassword = username + ":" + password;
        final String basicAuth = "Basic " + new String(new Base64().encode(userPassword.getBytes()));
        final Map<String, String> extraHeaders = new HashMap<>();
        extraHeaders.put("Authorization", basicAuth);
        pdfIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri = Uri.parse(pdfUrl);
                Intent target = new Intent(Intent.ACTION_VIEW);
                target.setDataAndType(uri,"*/*");
                Bundle bundle = new Bundle();
                bundle.putString("Authorization", basicAuth);
                target.putExtra(Browser.EXTRA_HEADERS, bundle);

                Intent intent = Intent.createChooser(target, "Open File");
                try {
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(getActivity(), "Please install PDF app", Toast.LENGTH_SHORT).show();
                }
            }
        });

我只需要向用户提供应用选择器,这样他/她就会选择使用女巫应用来打开文件,或者最好只是在他/她的设备上直接打开可用的PDF阅读器。

通过这个实现,我得到了应用程序选择器,当我尝试打开它加载的文件时,但最后它说它无法打开。

因此,使用此URL的练习是,当调用URL时,它会重定向到包含PDF文件本身的另一个URL。但我看不到第二个URL。此外,当我在浏览器中粘贴URL时,它会询问用户名和密码(这就是我需要Basic身份验证的原因)。

提前致谢。

1 个答案:

答案 0 :(得分:0)

很少(如果有的话)PDF查看者会为http活动支持https / ACTION_VIEW。实际上,它们都不会支持随机Intent附加内容,例如EXTRA_HEADERS

使用您最喜爱的HTTP客户端API(例如HttpUrlConnection,OkHttp)自行下载PDF。然后,使用ACTION_VIEW查看下载的PDF。