If Asynctask does not do lengthy background processing, then which method should I use

I use Asynctask most of the time, but in the current application the downloaded data is too large, so any other method that I can use to download the phonogram, I'm not sure if the handler is really for this purpose.

+4
source share
2 answers

but in the current application the downloaded data is too large, so the other method that I can use to load the background,

I disagree with your name because doInBackground is a method that is definitely used for long tasks. AsyncTask is AsyncTask a very powerful tool, also type safe.

But there is another solution.
Another clean and efficient approach is to use IntentService with ResultReceiver .

When you decide to use IntentService with ResultReceiver , here is a basic example


Just create a class that extends from the IntentService , then you must implement its onHandleIntent method

 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 the 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."); } } 

To start 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 IntentService do your job and

 receiver.send(PROGRESS_UPDATE, data); 

you can simply send information about your progress to update the UI .

Note: But see more information about IntentService over ResultReceiver .

+9
source

Quick suggestions:

  • You can execute multiple AsyncTask if the data is independent.
  • You can use the onProgressUpdate () method.
+1
source

All Articles