Search code examples
javaandroidrestandroid-asynctaskandroid-download-manager

How to move the download from main thread to background thread using Asynctask


I'm a beginner in Android developer and I'm trying to figure out how to download multiple files. I've went through a short YouTube tutorial that downloads a single PDF file but it is doing it in the main thread. There are some issues with this code that I want to take up as well but for now, I'd like to know how to incorporate AsyncTask into my code to download the PDF file in the background.

This is my code:

public class MainActivity extends AppCompatActivity {

    Button btn;
    DownloadManager downloadManager;
    private String exampleURL = "https://doc.lagout.org/programmation/Actionscript%20-%20Flash%20-%20Flex%20-%20Air/Flash%20Development%20for%20Android%20Cookbook%20-%20Labrecque%20-%20Packt%20%282011%29/Flash%20Development%20for%20Android%20Cookbook%20-%20Labrecque%20-%20Packt%20%282011%29.pdf";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = findViewById(R.id.download_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
                Uri uri = Uri.parse(exampleURL);
                DownloadManager.Request request = new DownloadManager.Request(uri);
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                Long reference = downloadManager.enqueue(request);
            }
        });
    }
}

I know some will ask what "Long reference" is doing there since its never used. Tbh idk as well and the individual neither explained nor used it anywhere but the download doesn't seem to work when I remove it from the code.

Another issue with this code is that unlike traditional downloading from apps like chrome, you do not get any sort of toast message telling you that your download started and you need to drag down your widget to see if there is a download going on. In other words, the screen on its down shows no indication of a download.


Solution

  • You're trying to solve a problem that doesn't exist.

    There's no point in putting the download request in an AsyncTask, since the DownloadManager already downloads asynchronously for you.