Issue
I'm a beginner in Android development. I'm trying to learn multi-threading and working with the internet so I'm doing that by downloading a PDF file from a link through the background thread using AsyncTask
. I have confusions about what the best way is to go about it.
Do I create the URI
and other necessary connectivity objects in the onCreate
or in the doInBackground
method of the AsyncTask
class?
To download just a single PDF file, what sort of objects do I need to call?
I have checked the documentation but I couldn't really understand it. I'd appreciate a layman's explanation and possibly pseudo-code.
Here is the code I have so far:
public class MainActivity extends AppCompatActivity {
Button downloadPDF;
DownloadingClass downPDF;
private static final String TAG = "omar.asynctaskdemo;";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String urlExample = "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");
downloadPDF = findViewById(R.id.download_pdf);
downPDF = new DownloadingClass();
downloadPDF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
downPDF.execute();
}
});
}
private class DownloadingClass extends AsyncTask<String, Integer, Void>{
@Override
protected Void doInBackground(String... strings) {
return null;
}
}
}
Solution
AsyncTask just runs your code in the background thread. To download a pdf file is like any other file.
You will require to use HttpUrlConnection
, Create a FileOutputStream
and write the inputstream
. Refer this
Have the above code executed in doInBackground
of AsyncTask class and better pass the url in the constructor and do everything inside the doInBackground
method. Since you don't want to block the UI thread.
Answered By - Binary Baba
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.