Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if Asynctask is not for doing long background processing then what method should i use

Tags:

android

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.

like image 932
Programmer Avatar asked Dec 26 '22 22:12

Programmer


1 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.

like image 113
Simon Dorociak Avatar answered Dec 29 '22 12:12

Simon Dorociak