in my application, I have a class for UI stuff, the name of which is "SettingActivity".
Then for doing some jobs in background, I bind this UI class(SettingActivity) to a Service. There are two predefined methods in that Service(defined in .aidl file), one is startTask(), the other one is stopTask().
Within startTask(), I made a call to an AsyncTask. But when I checked the name of the Looper of this AsyncTask. It is "main". In my opinion, an AsyncTask should start an another Thread other than the main Thread.
So does somebody know why this happens?
The codes are as follows:
@Override protected void onPreExecute() { super.onPreExecute(); Log.d(TAG, "onPreExecute "+Looper.myLooper().getThread().getName()); }
Then I will get main as the output.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .
doInBackground(Params) – This method is invoked on the background thread immediately after onPreExecute() finishes its execution. Main purpose of this method is to perform the background operations that can take a long time. The parameters of the Asynchronous task are passed to this step for execution.
Android App Development for Beginners Android AsyncTask going to do background operation on background thread and update on main thread. In android we cant directly touch background thread to main thread in android development. asynctask help us to make communication between background thread to main thread.
Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive. Android application runs on a single thread when launched.
An AsyncTask has several parts that you can override: a doInBackground
method that does, in fact, run on a separate thread, and three methods—onPreExecute
, onProgressUpdate
, and onPostExecute
—that run on the UI thread. (The default implementation of these methods do nothing and onProgressUpdate
only runs if you call publishProgress
, usually from within doInBackground
.) The purpose of onPostExecute
is to publish results (such as updating the view hierarchy, or setting text in a text view) that must be done on the UI thread. It also can post progress updates. In order for this to all work properly, the AsyncTask must be created, and the execute
method called, on the UI thread.
You must not call UI actions from within doInBackground
-- doing so will crash your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With