通过电子邮件发送数据库文件 Android

Email a db file Android

正在尝试通过电子邮件发送 SQLite 数据库。邮件发送成功,但没有附件。我的代码是:

Uri uri;
if(android.os.Build.VERSION.SDK_INT >= 4.2)
{
 uri = Uri.fromFile (
  new File (
   getApplicationContext().getApplicationInfo().dataDir + 
   "/databases/"+ MainActivity.accounts.getUserName()+ "D"+"/Dentist.db"
   )
  );
} else {
 uri = Uri.fromFile (
  new File (
   "/data/data/" + getApplicationContext().getPackageName() + 
   "/databases/"+MainActivity.accounts.getUserName()+ "D"+"/Dentist.db"
  )
 );
}

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("application/db");
shareIntent.putExtra(Intent.EXTRA_EMAIL,new String[] { "" });
shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Test");
shareIntent.putExtra(Intent.EXTRA_TEXT, "");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(shareIntent);

发送电子邮件的应用程序无权访问您的数据库文件。在将它附加到电子邮件之前,您必须将 db 文件复制到您的应用程序外部文件目录。

您可以通过

获取外部文件目录的路径
context.getExternalFilesDir(null)

试试这个代码,你必须传递你的数据库名称你想分享的电子邮件地址 数据库文件。

@SuppressWarnings("resource")
    public static void exportDatabse(Context ctx) {
        File backupDB = null;
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//" + ctx.getPackageName()
                        + "//databases//" + "Your_db_name" + "";
                File currentDB = new File(data, currentDBPath);
                backupDB = new File(sd, "Your_db_name");

                if (currentDB.exists()) {

                    FileChannel src = new FileInputStream(currentDB)
                            .getChannel();
                    FileChannel dst = new FileOutputStream(backupDB)
                            .getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        emailIntent.setType("*/*");
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                new String[] { "to_your_email_address@gmail.com" });

        Random r = new Random();

        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                "Local db " + r.nextInt());
        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(backupDB));
        ctx.startActivity(Intent.createChooser(emailIntent, "Export database"));
    }

完成

通过允许应用程序写入外部存储,确保您可以在发送文件之前成功导出文件。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />