Reputation: 31
I think this is a very simple question for many people in this community, however, I can't make this to work after several experiments; I would appreciate any help.
It is JAVA-android platform: The code needs to execute the next steps when the user clicks a button:
Make invisible the button (run in main thread)
Make visible a progress bar (run in main thread)
Download a file from internet (run in background thread)
Wait the download is completed
Make invisible the progress bar
Make visible again the button
That's it. It doesn't seem to be very difficult, however, it is not working as I need it.
This is the issue: Step 3 get executed before steps 1 and 2, ... I have tried several experiments with not success.
private void f1()
{
mDataBinding.btnPausePlay.setVisibility(btnVisibility);
mDataBinding.progressPausePlay.setVisibility(progressVisibility);
}
private void f2()
{
Thread xThread = new Thread( new Runnable()
{ @Override
public void run() // run in background thread
{ httpRequest_noBackgroundThread( urlStr, urlParams, fileStr, itf ); }
});
try
{
xThread.start();
xThread.join(); // wait for the thread to finish
}
catch( Exception e ){ e.printStackTrace(); }
}
private void f3()
{
f1();
f2();
// continues execution ...
}
###########################################################
private void f3()
{
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() ->
{
f1();
f2();
// continues execution ...
});
}
Upvotes: 0
Views: 105
Reputation: 163
To accomplish this, you have to use Executors
in Java. The below code will be done the job for you-
btnPausePlay.setOnClickListener(view -> {
btnPausePlay.setVisibility(View.GONE);
progressPausePlay.setVisibility(View.VISIBLE);
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> {
// Implement your file download code here i.e.
// httpRequest_noBackgroundThread( urlStr, urlParams, fileStr, itf );
handler.post(() -> {
btnPausePlay.setVisibility(View.VISIBLE);
progressPausePlay.setVisibility(View.GONE);
});
});
});
When you press the btnPausePlay button, then it will become invisible and the progress bar becomes visible. After that, once the download is completed reverse will happen.
Upvotes: 1