Android Intent保存电子邮件附件

时间:2014-05-23 07:59:41

标签: android file save intentfilter

我正在接收带有自定义文件扩展名的电子邮件(实际上是zip文件)。

当我尝试打开附件时,例如K9电子邮件应用程序并将其保存到我的应用程序的缓存目录,该zip文件已损坏,例如它没有打开文件管理器

private void importData(Uri data) {
    Log.d(TAG, data.toString());
      final String scheme = data.getScheme();

      if(ContentResolver.SCHEME_CONTENT.equals(scheme)) {
        try {
          ContentResolver cr = getApplicationContext().getContentResolver();
          InputStream is = cr.openInputStream(data);
          if(is == null) return;

          StringBuffer buf = new StringBuffer();            
          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
          String str;
          if (is!=null) {                           
              while ((str = reader.readLine()) != null) {   
                  buf.append(str);
              }             
          }     
          is.close();

          File outputDir = getApplicationContext().getCacheDir(); // context being the Activity pointer
          Log.d(TAG, "outputDir: " + outputDir.getAbsolutePath());

          String fileName = "test_seed.zip";
          Log.d(TAG, "fileName: " + fileName);

          File zipFile = new File(outputDir, fileName);
          FileWriter writer = new FileWriter(zipFile);
          try {
              writer.append(buf.toString());
              writer.flush();
              writer.close();
          } catch (IOException e) {
              Log.d(TAG, "Can't write to " + fileName, e);
          } finally {
              Toast.makeText(getApplicationContext(), "Zip key file saved to SDCard.", Toast.LENGTH_LONG).show();
          }
          // perform your data import here…

        } catch(Exception e) {
            Log.d("Import", e.getMessage(), e);
        }
    }
}

Uri字符串是

content://com.fsck.k9.attachmentprovider/668da879-32c8-4143-a3ec-e135d901c443/31/VIEW

这是我的意图过滤器:

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.EDIT" />
<category android:name="android.intent.category.DEFAULT" />
<data
    android:mimeType="application/*"
    android:host="*" 
    android:pathPattern=".*\\.odks" />
</intent-filter>

1 个答案:

答案 0 :(得分:1)

您的BufferedReader.readLine()是问题所在;它假定您的文件是一个很好的人类可读的文本文件,其中\ n表示行的结尾。 Zip文件不是那样的。因此,请调用InputStream和FileOutputStream的read()和write()方法。

这些方面的东西:

byte[] buffer = new byte[1024];
int n = 0;
while ((n = infile.read(buffer)) != -1) {
    outfile.write(buffer, 0, n);
}