我想允許我的Android應用程序的用戶導出SQLite數據庫文件來創建它們的內容。我當前的解決方案將文件複製到私有存儲(/data/data/com.package.name/files/Content.db
),然後爲該文件創建一個URI並打開共享對話框。這是行得通的,例如,允許我使用Dropbox導出數據庫文件。下面是我使用的代碼,從https://stackoverflow.com/a/2661882部分調整 -從Android應用程序共享SQLite數據庫,無中間副本
private void exportContent() {
copyContentToPrivateStorage();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("application/octet-stream");
Uri uri = new FileProvider().getDatabaseURI(this);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "Backup via:"));
}
private void copyContentToPrivateStorage() {
// From https://stackoverflow.com/a/2661882
try {
File data = Environment.getDataDirectory();
File sd = getFilesDir();
if (sd.canWrite()) {
String currentDBPath = "//data//com.package.name//databases//Content.db";
String backupDBPath = "Content.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
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) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
public class FileProvider extends android.support.v4.content.FileProvider {
public Uri getDatabaseURI(Context c) {
File exportFile = new File(c.getFilesDir(), "Content.db");
Uri uri = getUriForFile(c, "com.package.name.fileprovider", exportFile);
c.grantUriPermission("*", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
return uri;
}
}
好像我應該能夠直接從現有的數據庫路徑中創建一個URI,而不是做一箇中間副本。有沒有辦法做到這一點?
我可以繼續進行中間複製,但我認爲將數據庫的第二個副本保留在數據目錄中的時間超過必要的時間是個不好的做法。有沒有一種方法可以在選擇的應用程序使用URI共享文件後將其清除並刪除?
在你的應用程序之間共享數據,是你的期望? – 2015-03-31 18:44:16
這聽起來像一個非常糟糕的主意。您應該使用Contentproviders。 – wvdz 2015-03-31 18:45:04
如果我只是想讓另一個應用程序訪問某些數據,ContentProviders會很棒。在這種情況下,我想發送實際的SQLite數據庫文件。這主要是爲了將數據備份和導出到另一臺設備。我最終也可能會選擇雲解決方案,但我也希望允許用戶將自己的數據庫文件副本備份到其個人存儲上。 – Patrick 2015-04-01 18:30:19