Fundamentally you can use AsyncTask through which you would be able to achieve the above, if the download is strictly tied to the activity. However AsyncTask needs to be properly cancelled once user cancel or back out from activity. Also it provide basic mechanism to do the progress thing.
For example, imagine a simple async task (not the best implementation) but something like below
class SearchAsyncTask extends AsyncTask<String, Void, Void> {
SearchHttpClient searchHttpClient = null;
public SearchAsyncTask(SearchHttpClient client) {
searchHttpClient = client;
}
@Override
protected void onProgressUpdate(Void... values) {
// You can update the progress on dialog here
super.onProgressUpdate(values);
}
@Override
protected void onCancelled() {
// Cancel the http downloading here
super.onCancelled();
}
protected Void doInBackground(String... params) {
try {
// Perform http operation here
// publish progress using method publishProgress(values)
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute() {
// If not cancelled then do UI work
}
}
Now in your activity's onDestroy method
@Override
protected void onDestroy() {
Log.d(TAG, "ResultListActivity onDestory called");
if (mSearchTask != null && mSearchTask.getStatus() != AsyncTask.Status.FINISHED) {
// This would not cancel downloading from httpClient
// we have do handle that manually in onCancelled event inside AsyncTask
mSearchTask.cancel(true);
mSearchTask = null;
}
super.onDestroy();
}
However if you allow user to Download file even independent of activity (like it continues downloading even if user got away from Activity), I would suggest to use a Service which can do the stuff in background.
UPDATE: Just noticed there is a similar answer on Stackoverflow which explains my thoughts in further detail Download a file with Android, and showing the progress in a ProgressDialog