Android:如何引用DownloadManager下载的文件

Android: How to refer to the file downloaded by DownloadManager

我使用下载管理器Class下载了一个文本文件,我下载文件的代码是:

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

而且我有一个广播接收器来检查是否下载成功。如果下载成功,我会尝试在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");

另外,我已经把文件下载到外接存储了。我知道如果我没有添加这一行:

request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "test.txt");

当我向下载管理器发送请求时,文件将被下载到内部存储。在这种情况下如何引用该文件?

非常感谢。

更新: 如果我在广播接收器中成功接收到文件后添加此行:

String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

uriString给我

file:///storage/emulated/0/Download/test.txt

经过多次尝试,我找到了解决问题的方法。我不知道这是否是一个好的解决方案,但它似乎可行。我在广播接收器中成功接收到文件后添加了以下代码,即我添加的:

int filenameIndex = c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
String filename = c.getString(filenameIndex);
File file = new File(filename);

并删除了这段代码:

File file = new File(storage_directory,"test.txt");

之后:

if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {

这样做,即使系统重命名了文件,它也会引用新下载的文件。