使用如下方法在很多手机上出现发送的内容及主题丢失:
public static void sendEmail(Context context, String receiver, String subject, String body, File file) {
try {
Intent it = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + receiver)));
if (!TextUtils.isEmpty(subject)) {
it.putExtra(Intent.EXTRA_SUBJECT, subject);
}
if (!TextUtils.isEmpty(body)) {
it.putExtra(Intent.EXTRA_TEXT, body);
}
File file = new File(file);
if (file.exists()) {
it.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
}
context.startActivity(Intent.createChooser(it, "Send Email"));
} catch (Exception e) {
Log.e("sendEmail", e);
}
}
所以推荐使用如下发送邮件方法:
public static void sendEmail(Context context, String receiver, String subject, String body, File file) {
try {
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, new String[]{receiver});
it.setType("*/*");
if (!TextUtils.isEmpty(subject)) {
it.putExtra(Intent.EXTRA_SUBJECT, subject);
}
if (!TextUtils.isEmpty(body)) {
it.putExtra(Intent.EXTRA_TEXT, body);
}
if (file != null && file.exists()) {
it.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
}
context.startActivity(createEmailOnlyChooserIntent(context,it, receiver,"Send Email"));
} catch (Exception e) {
Log.e( "sendEmail", e);
}
}
通过匹配进行筛选:
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"+receiver));
getPackageManager().queryIntentActivities(intent, 0);
方法 createEmailOnlyChooserIntent 如下:
public static Intent createEmailOnlyChooserIntent(Context context,Intent source,String receiver,String chooserTitle) {
Stack<Intent> intents = new Stack<>();
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"+receiver));
List<ResolveInfo> activities = context.getPackageManager().queryIntentActivities(i, 0);
for(ResolveInfo ri : activities) {
Intent target = new Intent(source);
target.setPackage(ri.activityInfo.packageName);
intents.add(target);
}
if(!intents.isEmpty()) {
Intent chooserIntent = Intent.createChooser(intents.remove(0), chooserTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(new Parcelable[0]));
return chooserIntent;
} else {
return Intent.createChooser(source, chooserTitle);
}
}
最终效果很满意!!
网友评论