Issue
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.
Solution
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".
Answered By - AIMIN PAN
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.