我已經使用了下載管理器類下載一個文本文件,我下載的文件的代碼是:安卓:如何指通過下載管理器下載的文件
private long enqueue
private DownloadManager dm;
String server_ip = "http://192.168.0.1/";
Request request = new Request(Uri.parse(server_ip + "test.txt"));
// Store to common external storage:
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "test.txt");
enqueue = dm.enqueue(request);
而且我有一個boardcast接收器檢查下載是否成功。如果下載是成功的,我會盡量在一個TextView顯示txt文件:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
// Check if the download is successful
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
// Get the downloaded file and display the test.txt in a textView
File file = new File(storage_directory,"test.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
TextView tv = (TextView)findViewById(R.id.textView);
tv.setText(text);
}
catch (Exception e) {
//You'll need to add proper error handling here
}
}
}
}
}
}
的一個問題,我發現是,如果已經存在具有相同文件名的文件,「的text.txt」,該設備將新下載的文件重命名爲「text-1.txt」。因此,當我嘗試顯示新下載的文件時,它會顯示舊的「test.txt」文件。我想問一下我怎麼可以參考新的文件時,下載成功,而不是指定一個文件名像我所做的:
File file = new File(storage_directory,"test.txt");
另外,我還downloadeded文件到外部存儲。我知道,如果我沒有加入這一行:當我將請求發送到下載管理器
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "test.txt");
,該文件將被donwloaded到內部存儲。在這種情況下我如何參考文件?
非常感謝。
更新: 如果我加入這一行後收到的文件成功在廣播接收器:
String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
的uriString中給我
文件:///存儲/模擬/ 0 /下載/ test.txt
看看http://www.gadgetsaint.com/android/download-manager/#.WSK0Yut96Hs – ASP