存储在内部存储中的Zip文件的邮件附件无法正常工作

时间:2014-02-04 12:48:52

标签: android

我需要通过Mail附加一个zip文件,但是这里只发送不附带文件的消息是您的类型参考的代码

我们无法发送内部存储空间,因此我使用了contentProvider

 public class CachedFileProvider extends ContentProvider
    {
         private static final String CLASS_NAME = "CachedFileProvider";
            // The authority is the symbolic name for the provider class
        public static final String AUTHORITY = "com.example.sendmailwa.content.provider";

        private UriMatcher uriMatcher;

       @Override
       public boolean onCreate() {
           uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

           // Add a URI to the matcher which will match against the form
           // 'content://com.stephendnicholas.gmailattach.provider/*'
           // and return 1 in the case that the incoming Uri matches this pattern
           uriMatcher.addURI(AUTHORITY, "*", 1);
           return true;
       }
       @Override
       public ParcelFileDescriptor openFile(Uri uri, String mode)
               throws FileNotFoundException {

           String LOG_TAG = CLASS_NAME + " - openFile";

           Log.v(LOG_TAG,
                   "Called with uri: '" + uri + "'." + uri.getLastPathSegment());

           // Check incoming Uri against the matcher
           switch (uriMatcher.match(uri)) {

           // If it returns 1 - then it matches the Uri defined in onCreate
           case 1:

               // The desired file name is specified by the last segment of the
               // path
               // E.g.
               // 'content://com.stephendnicholas.gmailattach.provider/Test.txt'
               // Take this and build the path to the file
               String fileLocation = getContext().getCacheDir() + File.separator
                       + uri.getLastPathSegment();

               // Create & return a ParcelFileDescriptor pointing to the file
               // Note: I don't care what mode they ask for - they're only getting
               // read only
               ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(
                       fileLocation), ParcelFileDescriptor.MODE_READ_ONLY);
               return pfd;

               // Otherwise unrecognised Uri
           default:
               Log.v(LOG_TAG, "Unsupported uri: '" + uri + "'.");
               throw new FileNotFoundException("Unsupported uri: "
                       + uri.toString());
           }
       }

       // //////////////////////////////////////////////////////////////
       // Not supported / used / required for this example
       // //////////////////////////////////////////////////////////////

       @Override
       public int update(Uri uri, ContentValues contentvalues, String s,
               String[] as) {
           return 0;
       }

       @Override
       public int delete(Uri uri, String s, String[] as) {
           return 0;
       }

       @Override
       public Uri insert(Uri uri, ContentValues contentvalues) {
           return null;
       }

       @Override
       public String getType(Uri uri) {
           switch (uriMatcher.match(uri)) {
        // If it returns 1 - then it matches the Uri defined in onCreate
        case 1:
        return "application/zip"; // Use an appropriate mime type here
        default:
        return null;
        }
       }

       @Override
       public Cursor query(Uri uri, String[] projection, String s, String[] as1,
               String s1) {
           switch (uriMatcher.match(uri)) {
        // If it returns 1 - then it matches the Uri defined in onCreate
        case 1:
        MatrixCursor cursor = null;
        File file = new File( getContext().getCacheDir() + File.separator
        + uri.getLastPathSegment());
        if (file.exists()) {
        cursor = new MatrixCursor(new String[] {
        OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE });
        cursor.addRow(new Object[] { uri.getLastPathSegment(),
        file.length() });
        }

        return cursor;
        default:
        return null;
        }
       }

    }


Here is my MainActivity of sending Attachment file

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try{
            //createCachedFile(MainActivity.this,"test.txt","this is test content");
            createCachedFile(MainActivity.this,"test.zip","this is test content");
            TextView txt=(TextView)findViewById(R.id.txt);
            txt.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //sendmail();

                    File file = new File(MainActivity.this.getFilesDir() + "/" + "test.zip");
                    sendMail(file);
                }
            });

        }catch(Exception ex){}
    }
    private void sendmail()
    {
        try{
            //String path=Environment.getExternalStorageDirectory().toString()+"/";
            String path="test.txt";
            //String fileStringArray[]={path+"A.png",path+"B.png",path+"C.png"};
            //String zipDestinationString=path+"ZZ.zip";
            //new Zip(fileStringArray, zipDestinationString);
            String zipDestinationString="test.txt";
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"ranjith@softcraftsystems.com"});
            intent.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
            intent.putExtra(Intent.EXTRA_TEXT, "Email Message");
            //intent.setType("application/zip");
            intent.setType("plain/text");
            //intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + zipDestinationString));
            intent.putExtra(Intent.EXTRA_STREAM,
                        Uri.parse("content://" + CachedFileProvider.AUTHORITY + "/"
                                + zipDestinationString));
            startActivity(Intent.createChooser(intent, "Send Email"));
        }catch(Exception ex){
            Log.d("sendmail",ex.toString());
        }
    }
    private void sendMail(File outFile) {
        Uri uriToZip = Uri.fromFile(outFile);
        String zipDestinationString="test.zip";
        String sendText = "Dear friend,\n\n...";
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[] { "ranjith@softcraftsystems.com"});
        sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, sendText);
        sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Log of the test");
        sendIntent.setType("application/zip");
        sendIntent.putExtra(Intent.EXTRA_STREAM,
                Uri.parse("content://" + CachedFileProvider.AUTHORITY + "/"
                        + uriToZip));
    //   sendIntent.setType("image/jpeg");
    //   sendIntent.setType("message/rfc822");

         //sendIntent.putExtra(android.content.Intent.EXTRA_STREAM, uriToZip);
         startActivity(Intent.createChooser(sendIntent, "Send Attachment !:"));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public static void createCachedFile(Context context, String fileName,
            String content) throws IOException {

    File cacheFile = new File(context.getCacheDir() + File.separator
                + fileName);
    cacheFile.createNewFile();

    FileOutputStream fos = new FileOutputStream(cacheFile);
    OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8");
    PrintWriter pw = new PrintWriter(osw);

    pw.println(content);

    pw.flush();
    pw.close();
}
    public static Intent getSendEmailIntent(Context context, String email,
            String subject, String body, String fileName) {

    final Intent emailIntent = new Intent(
                android.content.Intent.ACTION_SEND);

    //Explicitly only use Gmail to send
    emailIntent.setClassName("com.google.android.gm","com.google.android.gm.ComposeActivityGmail");

    emailIntent.setType("plain/text");

    //Add the recipients
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                new String[] { email });

    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);

    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);

    //Add the attachment by specifying a reference to our custom ContentProvider
    //and the specific file of interest
    emailIntent.putExtra(
            Intent.EXTRA_STREAM,
                Uri.parse("content://" + CachedFileProvider.AUTHORITY + "/"
                        + fileName));

    return emailIntent;
}
    public class Zip {
        private static final int BUFFER = 2048;

        private String[] _files;
        private String _zipFile;

        /**
         * This class allows for the automated creation of Zip files when given a String array of file paths. 
         * 
         * @param files - String array containing the path of all the files to be zipped
         * @param zipFile - The destination of the Zip file.
         */
        public Zip(String[] files, String zipFile) {
            _files = files;
            _zipFile = zipFile;
            doZip();
        }

        /**
         * Private method to handle building a Zip file
         */
        private void doZip() {
            try {
                BufferedInputStream origin = null;
                FileOutputStream dest = new FileOutputStream(_zipFile);

                ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                        dest));

                byte data[] = new byte[BUFFER];

                for (int i = 0; i < _files.length; i++) {
                    System.out.println("Adding: " + _files[i]);
                    FileInputStream fi = new FileInputStream(_files[i]);
                    origin = new BufferedInputStream(fi, BUFFER);
                    ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
                    out.putNextEntry(entry);
                    int count;
                    while ((count = origin.read(data, 0, BUFFER)) != -1) {
                        out.write(data, 0, count);
                    }
                    origin.close();
                }

                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }     
}

那个test.txt工作正常但不是zip文件

0 个答案:

没有答案