I recently created an activity in my app. Now I wanted the user to download a .pdf file when he/she wants to view the guidelines. I wanted to implement this on a button. Any
It is really bad idea to download file in main thread.
Use separate Thread
for this
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//your downloading here
}
});
thread.start();
it`s better, but still not so good. There are some problems with it:
1) User know nothing about downloading
So better to show additional layout which overlays screen with progress bar, probably indeterminate if you want to write less code. Then after downloading is finished you just hide your layout.
You can use runOnUiThread
inside run
method in thread for it.
runOnUiThread(new Runnable() {
@Override
public void run() {
//just hide some popup
//or do what you want after downloading is finished
popupLayout.serVisibility(View.GONE);
}
});
2) If user will do action which re-creates activity/fragment (like changing screen orientaion) with running thread you will get memory leak and probably activity will not know about end of download.
There are few ways to solve this problem:
foreground service
. Its really goodthread.interrupt()
method in onDestroy
of your Activity
/Fragment
rxJava
/rxAndroid
(so you don not use threads at all, but you need some time for learn rxJava
)UPD
About threads
Not so bad tutorial about threads in android
You can use AsyncTask
instead of Thread
, but I highly recommend to use threads especially for long operations.