是否可以从不同线程并行多次调用Retrofit的execute()方法?

时间:2018-11-15 16:31:25

标签: java android multithreading retrofit

我需要使用Retrofit.using enqueue()方法从服务器下载mp3文件,响应回调出现在UI线程中。因此,我决定从工作线程使用execute()方法。但我的要求是,我需要并行下载多个mp3文件。以下是我的代码,能否请您告诉我这是一个好习惯还是建议我一种更好的方法。

@Override
public void onClick(View v) {
    final DownloadAndStoreMusic downloadAndStoreMusic = new DownloadAndStoreMusic(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                downloadAndStoreMusic.downloadLoadMusic(musicUrlForPerseFromServer, musicUrlforLocalStorage, actionString,categoryIndex,itemIndex);
            }
        }).start();
    }

在“下载”类中

public class DownloadAndStoreMusic {

private static final String TAG = "tag";
ApiInterfaceforMusicPersing apiInterfaceforMusicPersing;

Context mContext;

DownloadAndStoreMusic(Context mContext) {
    apiInterfaceforMusicPersing = RetrofitApiClientForMusicPersing.getClient().create(ApiInterfaceforMusicPersing.class);
    this.mContext = mContext;
}

public void downloadLoadMusic(final String musicUrlForPerseFromServer, final String musicUrlforLocalStorage, final String actionString,final int categoryIndex, final int itemIndex) {

   /* String[] split = url.split("/");
    final String pathToLocalStorage = url;  // We bought music location with category path
    String musicLink = split[1];*/
    Log.e("server", musicUrlForPerseFromServer);
    Log.e("perse", musicUrlforLocalStorage);

    Call<ResponseBody> responseBodyCall = apiInterfaceforMusicPersing.downloadMusic(musicUrlForPerseFromServer);

  /*  responseBodyCall.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {

            Log.e("music", "completed");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    writeResponseBodyToDisk(response.body(), musicUrlforLocalStorage, musicUrlForPerseFromServer, actionString,categoryIndex,itemIndex);
                }
            }).start();

        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(mContext, "Problem downloading audio", Toast.LENGTH_SHORT).show();
        }
    });*/

  try
  {
      Response<ResponseBody> execute = responseBodyCall.execute();
      ResponseBody body = execute.body();
      writeResponseBodyToDisk(body, musicUrlforLocalStorage, musicUrlForPerseFromServer, actionString,categoryIndex,itemIndex);
  }
  catch (Exception e)
  {
      Toast.makeText(mContext, "Problem downloading audio", Toast.LENGTH_SHORT).show();
      Log.e("exception"," : "+e+ " , "+musicUrlforLocalStorage);
  }


}

private boolean writeResponseBodyToDisk(ResponseBody body, String pathToLocalStorage, String musicUrlForPerseFromServer, String actionString, int categoryIndex, int itemIndex) {


    try {
        // todo change the file location/name according to your needs
       /* File audioParentDirectory;

        String[] split = musicUrlForPerseFromServer.split("/");
        String parentPath = split[0];
        String audioName = split[1];
         audioParentDirectory = new File(MyConstants.FILE_AUDIO_DIRECTORY, parentPath);

        File parent = new File(audioParentDirectory,parentPath);
        Log.e("audioparent",audioParentDirectory.getAbsolutePath());*/


        File audioDirectory = new File(pathToLocalStorage);
        Log.e("file", audioDirectory.getAbsolutePath());

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            byte[] fileReader = new byte[4096];

            long fileSize = body.contentLength();
            long fileSizeDownloaded = 0;

            inputStream = body.byteStream();
            outputStream = new FileOutputStream(audioDirectory);

            while (true) {
                int read = inputStream.read(fileReader);

                if (read == -1) {
                    break;
                }
                outputStream.write(fileReader, 0, read);

                fileSizeDownloaded += read;

                Log.e(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
            }

            outputStream.flush();

            Log.e("music","music downloaded : "+ audioDirectory.getAbsolutePath());
                }
            }
            return false;
        } 

1 个答案:

答案 0 :(得分:0)

您的方法是正确的,您将按预期下载多个mp3文件。