I have been using Asynctask most of time, but in the current app the data downloaded is too big so what other method i can use to do background downloading, i am not actually sure whether handler are for this purpose.
- you can use the handler as well bit not get the problem with Asynctask...Dheeresh Singh– Dheeresh Singh2012-06-23 10:38:57 +00:00Commented Jun 23, 2012 at 10:38
- 1There is no other method rather than doinBackGround.you can show progress of downloading task using onProgressUpdate.and use more than one asynctask for independent data.Samir Mangroliya– Samir Mangroliya2012-06-23 10:39:15 +00:00Commented Jun 23, 2012 at 10:39
- if you want you an use service as well to download data independently to your activity...Dheeresh Singh– Dheeresh Singh2012-06-23 10:42:39 +00:00Commented Jun 23, 2012 at 10:42
2 Answers
but in the current app the data downloaded is too big so what other method i can use to do background downloading,
I disagree with your title because doInBackground is a method that is exactly used for long tasks. So AsyncTask is very strong tool also type-safe.
But there is also another solution.
Another clean and efficient approach is use IntentService with ResultReceiver.
When you decide to use IntentService with ResultReceiver, here is basic example
Just create class that extends from IntentService, then you have to implement its method onHandleIntent
protected void onHandleIntent(Intent intent) { String urlLink = intent.getStringExtra("url"); ResultReceiver receiver = intent.getParcelableExtra("receiver"); InputStream input = null; long contentLength; long total = 0; int downloaded = 0; try { URL url = new URL(urlLink); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // ... Bundle data = new Bundle(); data.putInt("progress", (int) (total * 100 / contentLength)); receiver.send(PROGRESS_UPDATE, data); } //... } And implementation of onReceiveResult from ResultReceiver:
@Override public void onReceiveResult(int resultCode, Bundle resultData) { super.onReceiveResult(resultCode, resultData); if (resultCode == DownloadService.PROGRESS_UPDATE) { int progress = resultData.getInt("progress"); pd.setProgress(progress); pd.setMessage(String.valueOf(progress) + "% was downloaded sucessfully."); } } For start your Service just use
Intent i = new Intent(this, DownloadService.class); i.putExtra("url", <data>); // extra additional data i.putExtra("receiver", new DownloadReceiver(new Handler())); startService(i); So in your IntentService make your work and with
receiver.send(PROGRESS_UPDATE, data); you can simply send information about your progress for update UI.
Note: But see more information about IntentService nad ResultReceiver.