2016-05-29 64 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