2015-06-09 85 views
1

試圖通過電子郵件發送SQLite數據庫。電子郵件發送成功,但沒有附件。我的代碼是:通過電子郵件發送數據庫文件Android

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); 

回答

3

得到外部的文件目錄的路徑試試這個代碼,你必須通過上要份額分貝你的數據庫名電子郵件地址文件。

@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[] { "[email protected]" }); 

     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")); 
    } 

完成

1

發送電子郵件的應用程序無權訪問您的數據庫文件。在將它附加到電子郵件之前,您必須將數據庫文件複製到您的應用程序外部文件目錄中。

您可以通過

context.getExternalFilesDir(null)