2014-01-16 118 views
-3

我想從我的服務器通過URL下載音頻,當我點擊按鈕。Android下載音頻從服務器

我該怎麼做?

+0

你質疑並不清楚。你想做什麼 ? –

+0

謝謝先生,當我點擊按鈕時,我想通過URL從我的服務器下載音頻。 – user3187340

回答

2

對於從服務器下載文件,您可以使用以下代碼。

private class DownloadFile extends AsyncTask<String, Integer, String>{ 
@Override 
protected String doInBackground(String... url) { 
    int count; 
    try { 
     URL url = new URL("url of your .mp3 file"); 
     URLConnection conexion = url.openConnection(); 
     conexion.connect(); 
     // this will be useful so that you can show a tipical 0-100% progress bar 
     int lenghtOfFile = conexion.getContentLength(); 

     // downlod the file 
     InputStream input = new BufferedInputStream(url.openStream()); 
     OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.mp3"); 

     byte data[] = new byte[1024]; 

     long total = 0; 

     while ((count = input.read(data)) != -1) { 
      total += count; 
      // publishing the progress.... 
      publishProgress((int)(total*100/lenghtOfFile)); 
      output.write(data, 0, count); 
     } 

     output.flush(); 
     output.close(); 
     input.close(); 
    } catch (Exception e) {} 
    return null; 
} 

清單權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 

另請參考以下鏈接它可以幫助你:

how can i download audio file from server by url

Android:How to download the File from the server and save it in specific folder in sdcard

+0

它不工作?! – user3187340