Is it allowed to call Retrofit's execute() method multiple times in parallel from different threads?
I need to download mp3 file from server using retrofit.using enqueue() method ,the response callback comes in UI thread. So I decide to use execute() method from a worker thread. But my requirement is , I need to download multiple mp3 files in parallel. below is my code , Can u please let me know if it is a good practice or please suggest me a better approach.
@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();
On the Downloading class
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;
java android multithreading retrofit
add a comment |
I need to download mp3 file from server using retrofit.using enqueue() method ,the response callback comes in UI thread. So I decide to use execute() method from a worker thread. But my requirement is , I need to download multiple mp3 files in parallel. below is my code , Can u please let me know if it is a good practice or please suggest me a better approach.
@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();
On the Downloading class
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;
java android multithreading retrofit
add a comment |
I need to download mp3 file from server using retrofit.using enqueue() method ,the response callback comes in UI thread. So I decide to use execute() method from a worker thread. But my requirement is , I need to download multiple mp3 files in parallel. below is my code , Can u please let me know if it is a good practice or please suggest me a better approach.
@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();
On the Downloading class
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;
java android multithreading retrofit
I need to download mp3 file from server using retrofit.using enqueue() method ,the response callback comes in UI thread. So I decide to use execute() method from a worker thread. But my requirement is , I need to download multiple mp3 files in parallel. below is my code , Can u please let me know if it is a good practice or please suggest me a better approach.
@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();
On the Downloading class
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;
java android multithreading retrofit
java android multithreading retrofit
edited Nov 15 '18 at 18:22
hasibuzzaman chowdhury
asked Nov 15 '18 at 16:31
hasibuzzaman chowdhuryhasibuzzaman chowdhury
196
196
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Your approach is correct you will download multiply mp3 files as you expected.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53323935%2fis-it-allowed-to-call-retrofits-execute-method-multiple-times-in-parallel-fro%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Your approach is correct you will download multiply mp3 files as you expected.
add a comment |
Your approach is correct you will download multiply mp3 files as you expected.
add a comment |
Your approach is correct you will download multiply mp3 files as you expected.
Your approach is correct you will download multiply mp3 files as you expected.
answered Nov 15 '18 at 18:04
Oleh SokolovOleh Sokolov
7371514
7371514
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53323935%2fis-it-allowed-to-call-retrofits-execute-method-multiple-times-in-parallel-fro%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown