2015-07-28 58 views
0

我遇到了一個奇怪的問題。我編寫用於下載mp3文件的android應用程序。我用url下載mp3,它工作正常。但除VLC之外的任何播放器無法在設備上找到這些下載的mp3文件。如果我使用任何文件管理器,我可以找到這些文件,但他們沒有mp3標籤。Android。正確下載mp3

例如。

這是一個與我的應用程序一起下載的文件。我用FX文件管理器打開它的屬性。

enter image description here

而且它的MP3下載與其他程序(不是我)。正如你所看到的文件有MP3標籤(在屏幕的底部所示)

enter image description here

這是我的下載文件中的代碼:

@Override 
protected Void doInBackground(String... params) {    
    InputStream inputStream = null; 
    FileOutputStream fileOutput = null; 
    try { 
     URL url = new URL(params[0]); 
     File file = new File(path);    
     URLConnection urlConnection = url.openConnection(); 

     inputStream = urlConnection.getInputStream(); 
     fileOutput = new FileOutputStream(file); 

     int totalSize = urlConnection.getContentLength(); 
     int downloadedSize = 0; 

     byte[] buffer = new byte[16384]; 
     int bufferLength = 0; 

     while ((bufferLength = inputStream.read(buffer)) > 0) { 

      while(isPaused) { 
       sleep(); 
      } 

      if(isCancelled()) {     
       if(file.exists()) 
        file.delete(); 
       return null; 
      } 

      fileOutput.write(buffer, 0, bufferLength); 
      downloadedSize += bufferLength; 
      publishProgress(downloadedSize, totalSize); 
     } 

     if(totalSize > getFreeMemorySize()) { 
     //if(true) { 
      if(errorHandler != null) 
       errorHandler.onMemorySizeException(); 
      cancel(true); 
     }      
    } catch (IOException e) { 
     int i = e.hashCode(); 
     e.getStackTrace(); 
    } 
    finally { 
     try { 

      if(inputStream != null) 
       inputStream.close(); 
      if(fileOutput != null) 
       fileOutput.close();  

     } catch (IOException e) { 
      int i = e.hashCode(); 
      e.getStackTrace(); 
     } 
    } 
    return null; 
} 

我哪裏錯了?爲什麼用mp3播放器可以找到用我的應用程序下載的mp3文件?我怎麼修復它?

+0

什麼是您的文件路徑 – koutuk

+0

我不認爲這會解決問題,但你應該刷新你的流。 – user

+0

所有文件路徑顯示在scrinshots – JuniorThree

回答

1

你在觀察的是MediaStore不會不斷更新他的數據庫的事實。數據庫只有在重新啓動後和安裝SD卡後纔會更新。

如果您希望文件立即出現,您必須告訴MediaStore添加它們。

使用MediaScannerConnection.scanFile方法通知MediaStore。 (MediaScannerConnection doucumentation)請注意,您可以一次添加多個文件/路徑。另外值得注意的是,這種方法是異步的,文件被添加到一個單獨的進程中,這可能需要一些時間 - 操作完成後會通知您。

MediaScannerConnection.scanFile(
    context, 
    new String[]{file.getAbsolutePath()}, 
    null, 
    new OnScanCompletedListener() { 
    @Override 
    public void onScanCompleted(String path, Uri uri) { 
     // only at this point are files in MediaStore 
    } 
    }); 
+0

謝謝!我希望這會有所幫助! – JuniorThree