Reputation: 1
My application starts with a request to the server to get a list of urls. I want to download all these files(html,css and js files) from the urls. But I want these downloads to happen in the background without interfering with the performance of other activities.
I had an approach of making a Volley Request with an AsyncTask inside onResponse().
But Android is been throwing me warning like "Too much work happening in MainActivity"
Upvotes: 0
Views: 1182
Reputation: 2164
Since downloading it to a filesystem is what you're looking for and also need it to happen completely in background, you can try the DownloadManager
system service:
The code for which looks like:
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request pdfDownloadRequest = new DownloadManager.Request(Uri.parse(
/*url endpoint here*/));
pdfDownloadRequest.allowScanningByMediaScanner();
pdfDownloadRequest.setDescription("Can add custom description here.. ");
pdfDownloadRequest.setTitle("This sets a title for the download foreground notification");
pdfDownloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
pdfDownloadRequest.setVisibleInDownloadsUi(true);
// once the request is set, just add it to the download manager and it will handle it for you..
downloadManager.enqueue(pdfDownloadRequest);
DownloadManager
is a foreground system service, check the doc here
Also as you can see in my code, i've used it to download a PDF file, you can use this system service to download files as heavy as an entire movie :)
Upvotes: 0
Reputation: 606
You Should definitely try Async Task for the same
public class Sample extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
new BackGroundTask().execute();
}
class BackGroundTask extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected String doInBackground(Void... arg0)
{
//method
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
}
}
}
Upvotes: 1