Android 内部存储器中存储有Zip文件的邮件附件不工作
我需要通过邮件附上一个zip文件,但只发送邮件而不发送附加文件这里是代码供您参考 我们无法发送内部存储,因此我使用contentProviderAndroid 内部存储器中存储有Zip文件的邮件附件不工作,android,Android,我需要通过邮件附上一个zip文件,但只发送邮件而不发送附加文件这里是代码供您参考 我们无法发送内部存储,因此我使用contentProvider public class CachedFileProvider extends ContentProvider { private static final String CLASS_NAME = "CachedFileProvider"; // The authority is the symbol
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();
}
}
}
}
公共类CachedFileProvider扩展了ContentProvider
{
私有静态最终字符串CLASS\u NAME=“CachedFileProvider”;
//authority是提供程序类的符号名
public static final String AUTHORITY=“com.example.sendmailwa.content.provider”;
私人UriMatcher UriMatcher;
@凌驾
公共布尔onCreate(){
uriMatcher=新的uriMatcher(uriMatcher.NO_匹配);
//向匹配器添加一个URI,该URI将与表单匹配
// 'content://com.stephendnicholas.gmailattach.provider/*'
//如果传入Uri与此模式匹配,则返回1
addURI(AUTHORITY,“*”,1);
返回true;
}
@凌驾
公共ParcelFileDescriptor openFile(Uri,字符串模式)
抛出FileNotFoundException{
字符串LOG\u TAG=CLASS\u NAME+“-openFile”;
Log.v(Log_标签,
使用uri调用:“+uri+”。“+uri.getLastPathSegment());
//根据匹配器检查传入Uri
开关(uriMatcher.match(uri)){
//如果返回1-则与onCreate中定义的Uri匹配
案例1:
//所需的文件名由文件的最后一段指定
//路径
//例如。
// 'content://com.stephendnicholas.gmailattach.provider/Test.txt'
//获取该文件并构建该文件的路径
字符串fileLocation=getContext().getCacheDir()+File.separator
+getLastPathSegment();
//创建并返回指向文件的ParcelFileDescriptor(&R)
//注:我不在乎他们要求什么模式-他们只会得到
//只读
ParcelFileDescriptor pfd=ParcelFileDescriptor.open(新文件(
文件位置),ParcelFileDescriptor.MODE\u只读);
返回pfd;
//否则无法识别的Uri
违约:
Log.v(Log_标记,“不受支持的uri:”“+uri+””);
抛出新的FileNotFoundException(“不支持的uri:”
+uri.toString());
}
}
// //////////////////////////////////////////////////////////////
//此示例不支持/使用/需要
// //////////////////////////////////////////////////////////////
@凌驾
公共int更新(Uri、ContentValues、ContentValues、字符串s、,
字符串[]as){
返回0;
}
@凌驾
public int delete(Uri、字符串s、字符串[]as){
返回0;
}
@凌驾
公共Uri插入(Uri、ContentValues和ContentValues){
返回null;
}
@凌驾
公共字符串getType(Uri){
开关(uriMatcher.match(uri)){
//如果返回1-则与onCreate中定义的Uri匹配
案例1:
返回“application/zip”;//在此处使用适当的mime类型
违约:
返回null;
}
}
@凌驾
公共游标查询(Uri、字符串[]投影、字符串s、字符串[]as1、,
字符串s1){
开关(uriMatcher.match(uri)){
//如果返回1-则与onCreate中定义的Uri匹配
案例1:
MatrixCursor=null;
File File=新文件(getContext().getCacheDir()+File.separator
+getLastPathSegment());
if(file.exists()){
游标=新矩阵选择器(新字符串[]{
OpenableColumns.DISPLAY_NAME,OpenableColumns.SIZE});
cursor.addRow(新对象[]{uri.getLastPathSegment(),
file.length()});
}
返回光标;
违约:
返回null;
}
}
}
这是我发送附件文件的主要活动
公共类MainActivity扩展了活动{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
试一试{
//createCachedFile(MainActivity.this,“test.txt”,“这是测试内容”);
createCachedFile(MainActivity.this,“test.zip”,“这是测试内容”);
TextView txt=(TextView)findViewById(R.id.txt);
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
//sendmail();
File File=新文件(MainActivity.this.getFilesDir()+“/”+“test.zip”);
发送邮件(文件);
}
});
}捕获(例外情况除外){}
}
私有void sendmail()
{
试一试{
//字符串路径=Environment.getExternalStorageDirectory().toString()+“/”;
字符串path=“test.txt”;
//字符串fileStringArray[]={path+“A.png”,path+“B.png”,path+“C.png”};
//字符串zipDestinationString=path+“ZZ.zip”;
//新Zip(fileStringArray、zipDestinationString);
字符串zipDestinationString=“test.txt”;
意向意向=新意向(意向.行动\发送);
intent.putExtra(intent.EXTRA_电子邮件,新字符串[]{”ranjith@softcraftsystems.com"});
intent.putExtra(intent.EXTRA_主题,“电子邮件主题”);
intent.putExtra(intent.EXTRA_文本,“电子邮件”);
//intent.setType(“应用程序/zip”);
intent.setType(“纯/文本”);
//intent.putExtra(intent.EXTRA_STREAM,Uri.parse(“文件:/”+zipDestinationString));
我