首先,我们需要使用FileProvider获取文件的URI。接下来,我们可以使用Intent创建一个新的电子邮件,其中包含文件URI的片段。最后,在启动电子邮件应用程序之前,我们需要检查用户是否已经授予发送电子邮件的权限。
以下是示例代码:
//获取文件URI File file = new File(filePath); Uri uri = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file); } else { uri = Uri.fromFile(file); }
//创建新电子邮件 Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.setType("text/plain"); intent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//检查权限 if (intent.resolveActivity(context.getPackageManager()) != null) { context.startActivity(intent); } else { //应用程序没有安装。打开Play商店页面。 Intent playStoreIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.gm")); context.startActivity(intent); }