我已经使用了下载管理器类下载一个文本文件,我下载的文件的代码是:安卓:如何指通过下载管理器下载的文件
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