How to download a file after clicking a button (Android Studio)

前端 未结 2 1137
粉色の甜心
粉色の甜心 2020-12-31 23:23

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

2条回答
  •  轮回少年
    2021-01-01 00:06

    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:

    • You can block screen orientation at this screen, at least while downloading. Probably easiest way in your case.
    • You can use downloading in foreground service. Its really good
      practice, but you will have to learn about services.
    • You can try to interrupt downloading by calling thread.interrupt() method in onDestroy of your Activity/Fragment
    • You can use something like 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.

提交回复
热议问题