2016-05-29 84 views
3

我已经使用了下载管理器类下载一个文本文件,我下载的文件的代码是:安卓:如何指通过下载管理器下载的文件

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

+0

看看http://www.gadgetsaint.com/android/download-manager/#.WSK0Yut96Hs – ASP

回答

3

有很多尝试,我找到了一种方法来解决我的问题EM。我不知道这是否是一个好的解决方案,但它似乎工作。我下面的代码添加后收到的广播接收器成功的文件,这是我补充说:

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

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

+0

查询下载管理器确实是获取本地文件的方法。如果您在下载完成之前不需要本地文件名,那么这就是要走的路。 – user149408

+0

在API 24中不推荐使用COLUMN_LOCAL_FILENAME,并在Nougat中引发SecurityException – roplacebo