我想在使用DownloadManager点击按钮时更新应用程序的sqlite数据库。
但它说“java.lang.IllegalArgumentException:Not a file URI:/data/user/0/com.example.laudien.listviewtesting/databases/Employees”
我做错了什么?我需要获得许可吗?互联网许可已经在清单中。
以下是我的updateDb()方法的代码:
private void updateDb() {
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); // create download manager
DownloadFinishedReceiver receiver = new DownloadFinishedReceiver(); // create broadcast receiver
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); // register the receiver
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DATABASE_URL)); // create a download request
// delete database file if it exists
File databaseFile = new File(getDatabasePath(DATABASE_NAME).getAbsolutePath());
if(databaseFile.exists())
databaseFile.delete();
request//.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN) // not visible
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI) // only via wifi
.setDestinationUri(Uri.parse("file:" + getDatabasePath(DATABASE_NAME).getAbsolutePath())); // set path in app dir
downloadManager.enqueue(request); // enqueue the download request
}
答案 0 :(得分:1)
您的路径/data/user/0/com.example.laudien.listviewtesting
是您应用的私密内存。您是使用getFilesDir()
获得的。其他应用无法访问。包括下载管理器。请改用getExternalStorageDirectory()
给出的外部记忆。
答案 1 :(得分:0)
对于想要将敏感文件下载到应用的私有文件夹的任何人,我不得不说下载管理器无法访问内部存储中的这些文件夹。 但解决方案是在广播接收器中移动下载的文件。 例如将这样的行放在 BroadcastReceiver 中:
String destinationFileName = "test.mp4";
String filePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
copyFile(Uri.parse(filePath).getPath(), context.getFilesDir() + "/" + destinationFileName);
和 copyFile 是这样的方法:
private void copyFile(String inFileName, String outFileName) throws IOException {
InputStream myInput = new FileInputStream(inFileName);
OutputStream myOutput = new FileOutputStream(outFileName);
// Transfer bytes from the input file to the output file
byte[] myBuffer = new byte[1024];
int length;
while ((length = myInput.read(myBuffer)) > 0)
myOutput.write(myBuffer, 0, length);
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}