在Android中后台下载多个MP3文件

时间:2019-04-04 12:25:00

标签: java android

等级:初学者
语言:Java
IDE:Android Studio
案例:在后台连续从多个URL下载多个MP3文件。
问题:循环下载任务以下载所有URL。 歌曲确实按以下路径下载,但并未完全下载(每首歌曲的下载时间为3秒/ 4秒,基本上更少)。 不知道出什么问题,如果我能得到任何帮助,那将是很好的

  • 从API接收mp3网址
  • 使用以下代码下载它们。 (问题)
  • 获取所有路径并将其存储在数据库中
  • 获取路径并连续一个接一个地播放。

    private class DownloadTask extends AsyncTask<SongDetails, Integer, String> {
    Context context;
    
    public DownloadTask(Context context) {
        this.context = context;
    }
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Utilities.showProgressDialog(getActivity(), getFragmentManager());
    }
    
    @Override
    protected String doInBackground(SongDetails... songDetails) {
        for (SongDetails songs : songDetails
        ) {
            donwloadsong(songs);
        }
        return null;
    }
    
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Utilities.dismissProgressDialog();
    }
    }
    
    
    
    
     for (SongDetails songs : songDetails
        ) {
            downloadTask(songs);
        }
    
    
     public void downloadTask(SongDetails songs){
       HttpURLConnection httpURLConnection = null;
       try {
         URL url = new URL(songs.getUrl());
         httpURLConnection = (HttpURLConnection) url.openConnection();
         httpURLConnection.setRequestMethod("GET");
         httpURLConnection.connect();
    
        int fileLength = httpURLConnection.getContentLength();
             InputStream inputStream = new 
        BufferedInputStream(url.openStream(), 8192);
        OutputStream outputStream1;
        outputStream1 = new 
        FileOutputStream(Environment.getExternalStorageDirectory() + "/gbeduwarssongs/" + songDetails.getTitle().trim() + ".mp3");
        int count = 0;
             byte data[] = new byte[1024];
        int buffer_length;
    
        while ((buffer_length = inputStream.read(data)) != -1) {
            outputStream1.write(data, 0, count);
              count += buffer_length;
        }
        outputStream1.flush();
        outputStream1.close();
        inputStream.close();
    
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Error", "Download Error Exception " + e.getMessage());
    } finally {
        if (httpURLConnection != null)
            httpURLConnection.disconnect();
      }
    }
    

2 个答案:

答案 0 :(得分:0)

宁可在新线程中调用迭代,也要先使用迭代,然后在每次迭代中启动新线程。希望对您有帮助。我正在发布代码以帮助您。

for (SongDetails songs : songDetails) {
        new DownloadTask(pass your song object in constructor).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

,然后在doInBackground中调用您的下载方法。

答案 1 :(得分:0)

我愿意为此使用DownloadManagerworkmanager。 AsyncTask使用了一个坏主意。 memory leak有问题。 asyncTask仅使用one thread

The same question