0

I'm trying to build a demo app with 2 buttons, one downloads a video and the other downloads a PDF. I want to take care of the downloading in the background thread through AsyncTask. So far I have starter code with implemented methods. I haven't added the code for what I want to download yet because I want to figure out the logic behind separate downloads so for now, I have Log messages.

This is the code:

public class MainActivity extends AppCompatActivity {
    Button downloadVideo, downloadPDF;
    DownloadingClass downloadingClass = new DownloadingClass();
    private static final String TAG = "omar.asynctaskdemo;";

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

        downloadVideo = findViewById(R.id.download_video);
        downloadPDF = findViewById(R.id.download_pdf);

        downloadVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {}
        });

        downloadPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {}
        });
    }

    private class DownloadingClass extends AsyncTask<Void, Void, Void>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.d(TAG, "doInBackground: Before");
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Log.d(TAG, "doInBackground: After");
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            Log.d(TAG, "doInBackground: Progress");
        }

        @Override
        protected Void doInBackground(Void... voids) {
            Log.d(TAG, "doInBackground: Content to download");
            return null;
        }
    }
}

I'd appreciate a concise explanation on how to go about it.

Onur-Andros Ozbek
  • 2,998
  • 2
  • 29
  • 78

2 Answers2

2

Don't do this

DownloadingClass downloadingClass = new DownloadingClass();

Always create just before you kick of the task:

new DownloadingClass().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

This is because you can't reuse the AsyncTask. It has status and will not run again once status is "Finished".

AIMIN PAN
  • 1,563
  • 1
  • 9
  • 13
1

if you have same input/output type in both download methods u can use same DownloadingClass by Declaring an object for each methods , like :

DownloadingClass downloadPDF = new DownloadingClass();
DownloadingClass downloadVideo = new DownloadingClass();

then just call downloadPDF.execute();/downloadVideo.execute();

or u can manage them by ExecutorService : How to wait for all threads to finish, using ExecutorService?

Ali Reza
  • 104
  • 6