“AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.” – developer.android
Async task class definition
class AsyncTaskClassName extends AsyncTask<argumentType, progrssValueType, taskResultType> { //inputarg can contain array of values protected taskResultType doInBackground(argumentType... inputarg) { //------- //-- Your Long running task here ---- int count = inputarg.length; for (int i = 0; i < count; i++) { Log.i("from Async task", inputarg[i] ); } //------- publishProgress(progrssValue)); return taskresult; } protected void onProgressUpdate(progrssValueType... progress) { //update the progress setProgressPercent(progress[0]); } //this will call after finishing the doInBackground function protected void onPostExecute(taskResultType result) { // Update the ui elements //show some notification showDialog("Task done "+ result); } }
starting task
new AsyncTaskClassName().execute(arg1, arg2, etc );
Or we can execute directly
new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { //long running task return null ; } @Override protected void onPostExecute(Void x) { //update the ui elemets } }.execute();
ref : https://developer.android.com/reference/android/os/AsyncTask.html
The UI element you are updating might become invalid by the time your onPostExecute() will be called, a better approach will be to pass the weakreference of the view you want to update and check if it is still valid before doing some operation on it.
Something like this:
You can pass the view itself which you would want to update instead of context, say like ProgressBar and store it in weakreference.
Thanks for the support sanket
That’s helpful! The onPreExecute function will happen on the main thread. It allows you to set up the work you’re about to do. Then the doInBackground function will execute on a worker thread actually doing the computation.
Source: https://techshali.com/asynctask-android/
Thanks