我正在尝试使用文件提供商将pdf附加到Gmail。它在安卓6.0上运行,但表示"无法附加文件">
fun startFileShareIntent(filePath: String, context: Context?) {
try {
val file = File(filePath)
val uri = FileProvider.getUriForFile(context!!, "com.trust.inspakt.android.provider", file)
val intent = ShareCompat.IntentBuilder.from(context as Activity)
.setType("application/pdf")
.setStream(uri)
.setChooserTitle("Choose bar")
.createChooserIntent()
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivity(intent)
} catch (e: Exception) {
e.printStackTrace()
}
}
根据您的问题,我认为它在Android 7.0及更高版本上运行?
在Android 6.0中,不需要文件提供程序。这是我用来将csv文件附加到gmail的Java代码。这适用于从Android 6.0到Android 11的我。
/* This is the filename or file URI, depending on what Android version you have
and how you got the filename */
String fileInfo;
final Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("message/rfc822");
emailIntent.putExtra(Intent.EXTRA_EMAIL,"example@gmail.com");
emailIntent.putExtra(Intent.EXTRA_SUBJECT,"subject");
emailIntent.putExtra(Intent.EXTRA_TEXT,emailBody);
//add file to email according to build type
if (Build.VERSION.SDK_INT>=Q){
Uri path = Uri.parse(fileInfo);
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
}
else if (Build.VERSION.SDK_INT>M) {
File test_result = new File(fileInfo);
String authority = context.getApplicationContext().getPackageName() + ".provider";
Uri path = FileProvider.getUriForFile(context.getApplicationContext(),authority,test_result);
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
}
else {
File test_result = new File(fileInfo);
Uri path = Uri.fromFile(test_result);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
}
//send email
context.startActivity(emailIntent);