【问题标题】:Send a pdf on an default Email Client - Android Aplication [duplicate]在默认电子邮件客户端上发送 pdf - Android 应用程序 [重复]
【发布时间】:2015-07-20 13:44:26
【问题描述】:

我需要在消息中发送 PDF 文件附件,我有一个按钮调用一个函数,该函数打开一个 Intent 并填写了消息、电子邮件地址和主题,但我还需要 PDF 文件已附加。

这是我的代码,我找不到我的错误,有人可以帮助我吗?

 public void initializeWebView() {
        // Initialize the webview

        webView.setResourceClient(new XWalkResourceClient(webView) {
            @Override
            public boolean shouldOverrideUrlLoading(XWalkView view, String stringUrl) {

                if(stringUrl.equals(baseUrl)) {
                    return false;
                }

                // mailto links will be handled by the OS.
                if (stringUrl.startsWith("mailto:")) {
                    Uri uri = Uri.parse(stringUrl);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    String fileName = "bouhnik.pdf";
                    String filePath = (Configuration.getMagazineAssetPath()).toString()+ File.separator  + fileName;
                    Context c = getActivity().getApplicationContext();
                    File file = null;
                    FileOutputStream fos = null;
                    try {

                        InputStream is = c.getAssets().open(filePath);

                        int size = is.available();
                        byte[] buffer = new byte[size];
                        is.read(buffer);
                        is.close();


                        fos = new FileOutputStream(file);
                        fos.write(buffer);
                        fos.close();


                    } catch (IOException e) {
                        Log.i("Ferrou",e.toString());
                        e.printStackTrace();
                    }
                    if (!file.exists() || !file.canRead()) {
                        return false;
                    }
                    intent.putExtra(intent.EXTRA_STREAM, file.getPath());
                    intent.setClassName("com.android.email", "com.android.mail.compose.ComposeActivity");
                    intent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
                    WebViewFragment.this.startActivity(Intent.createChooser(intent, "Send email..."));

                } else {
                    try {
                        URL url = new URL(stringUrl);


                        // We try to remove the referrer string to avoid passing it to the server in case the URL is an external link.
                        String referrer = "";
                        if (url.getQuery() != null) {
                            Map<String, String> variables = Configuration.splitUrlQueryString(url);
                            String finalQueryString = "";
                            for (Map.Entry<String, String> entry : variables.entrySet()) {
                                if (entry.getKey().equals("referrer")) {
                                    referrer = entry.getValue();
                                } else {
                                    finalQueryString += entry.getKey() + "=" + entry.getValue() + "&";
                                }
                            }
                            if (!finalQueryString.isEmpty()) {
                                finalQueryString = "?" + finalQueryString.substring(0, finalQueryString.length() - 1);
                            }
                            stringUrl = stringUrl.replace("?" + url.getQuery(), finalQueryString);
                        }
                        // Remove referrer from query string
                        if (!url.getProtocol().equals("file")) {
                            if (referrer.equals(WebViewFragment.this.getActivity().getString(R.string.url_external_referrer))) {
                                Uri uri = Uri.parse(stringUrl);
                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                WebViewFragment.this.startActivity(intent);
                            } else if (referrer.toLowerCase().equals(WebViewFragment.this.getActivity().getString(R.string.url_baker_referrer))) {
                                ((IssueActivity) WebViewFragment.this.getActivity()).openLinkInModal(stringUrl);
                                return true;
                            } else {
                                return false;
                            }
                        } else {
                            stringUrl = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
                            int index = ((IssueActivity) WebViewFragment.this.getActivity()).getJsonBook().getContents().indexOf(stringUrl);
                            if (index != -1) {
                                Log.d(this.getClass().toString(), "Index to load: " + index + ", page: " + stringUrl);
                                ((IssueActivity) WebViewFragment.this.getActivity()).getViewPager().setCurrentItem(index);
                                view.setVisibility(View.GONE);
                            } else {
                                // If the file DOES NOT exist, we won't load it.
                                File htmlFile = new File(url.getPath());
                                if (htmlFile.exists()) {
                                    return false;
                                }
                            }
                        }
                    } catch (MalformedURLException | UnsupportedEncodingException ex) {
                        Log.d(">>>URL_DATA", ex.getMessage());
                    }
                }

                return true;
            }
        });

        // Set UI Client (Start stop animations)
        webView.setUIClient(new XWalkUIClient(webView) {

            @Override
            public void onPageLoadStopped(XWalkView view, String url, LoadStatus status) {
                if(!url.isEmpty() && status == LoadStatus.FINISHED) {
                    if(isUserVisible) {
                        webView.resumeTimers();
                    }else{
                        webView.pauseTimers();
                    }

                }
            }
        });
        webView.load(baseUrl, null);
    } 

【问题讨论】:

  • 我不知道.-。我现在总是运行,我收到这个异常:“java.io.FileNotFoundException: file:/android_asset/books/bouhnik.pdf: open failed: ENOENT (No such file or directory)”
  • 检查uri 是否解析为实际文件,并尝试在该代码块中记录文件内容(Log.d),以确保文件内容实际可读。
  • 当我到达这一行时:尝试 { AssetManager am = c.getAssets(); ***** InputStream is = am.open("books/"+fileName);他们给了我一个例外“FileNotFound”,但我有这个路径和这个文件。

标签: java android email-attachments


【解决方案1】:

非常感谢大家!!

我解决了我的问题,将 Intent 的类型更改为:

Intent emailIntent = new Intent(Intent.ACTION_SEND);

因为这对电子邮件命令更好,所以我定义了一个 emailUri,其中:

emailUri = Uri.fromFile(file.getAbsoluteFile());

因为这会得到一个包含文件的绝对路径,并且当电子邮件客户端打开时,它会打开这个文件,而不是路径。

我根据自己的意图添加了一个类型,但我选择了附件的类型,因此我定义了:

 emailIntent.setType("application/pdf");

最后:

emailIntent.putExtra(Intent.EXTRA_STREAM, uriMail);
 startActivity(emailIntent);

现在可以了!!谢谢:D

【讨论】:

    【解决方案2】:

    您的文件路径似乎有问题。仔细检查一下。那么

    1 - 您需要在应用程序的包名中添加context.getPackageName()

    private String path = Environment.getExternalStorageDirectory().getPath() + context.getPackageName() +  "books/"+fileName;
    

    2 - 在您的 AndroidManifest.xml 中声明权限

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-07
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多