In Android, AsyncTask (Asynchronous Task) allows us to run the instruction in the background and then synchronize again with our main thread. This class will override at least one method i.e doInBackground(Params) and most often will override second method onPostExecute(Result).

AsyncTask class is used to do background operations that will update the UI(user interface). Mainly we used it for short operations that will not effect on our main thread.

AsyncTask class is firstly executed using execute() method. In the first step AsyncTask is called onPreExecute() then onPreExecute() calls doInBackground() for background processes and then doInBackground() calls onPostExecute() method to update the UI.


Table Of Contents [hide]

  • 1 Need of AsyncTask In Android:
  • 2 Syntax of AsyncTask In Android:
  • 3 Executions of AsyncTask class from main thread:
  • 4 AsyncTask’s generic types In Android:
  • 5 Method of AsyncTask In Android:
  • 6 Rules of AsyncTask:
  • 7 AsyncTask Example In Android Studio:

Need of AsyncTask In Android:

By default, our application code runs in our main thread and every statement is therefore execute in a sequence. If we need to perform long tasks/operations then our main thread is blocked until the corresponding operation has finished. For providing a good user experience in our application we need to use AsyncTasks class that runs in a separate thread. This class will executes everything in doInBackground() method inside of other thread which doesn’t have access to the GUI where all the views are present. The onPostExecute() method of this class synchronizes itself again with the main UI thread and allows it to make some updating. This method is called automatically after the doInBackground method finished its work.


Syntax of AsyncTask In Android:

To use AsyncTask you must subclass it. The parameters are the following AsyncTask . Here is the

Syntax of AsyncTask class:

 /**     * Login BackGround Operation     */    class LoginAsyncTask extends AsyncTask{        private String username;        private String password;        private ProgressDialog progressDialog;        public LoginAsyncTask(String username, String password){            this.username = username;            this.password = password;        }        @Override        protected void onPreExecute() {            super.onPreExecute();            progressDialog = ProgressDialog.show(LoginActivity.this,                    "请等待...", "正在登陆中...", true, false);        }        @Override        protected String doInBackground(Void... params) {            Map map = new HashMap<>();            map.put("j_username", username + ",undergraduate");            map.put("j_password", password);            try {                final CookieStore cookieStore = HttpUtils.postWithCookies(                        ConstVal.LOGIN_URL, map);                final String result = HttpUtils.get(ConstVal.CHECK_LOGIN_SUCCESS_URL, cookieStore);                System.out.println("result -->" + result);                UserInfo userInfo = UserInfo.getInstance();                userInfo.setCookieStore(cookieStore);                userInfo.setUsername(username);                userInfo.setPassword(password);                return result;            } catch (Exception e) {//network exception                e.printStackTrace();                return null;            }        }        @Override        protected void onPostExecute(String s) {            super.onPostExecute(s);            progressDialog.dismiss();            String result = s;            if (result == null){                Toast.makeText(LoginActivity.this, "请检查网络配置",                        Toast.LENGTH_SHORT).show();            }else if(result.length() > 100){//登录失败                Toast.makeText(getApplicationContext(),                        "登录失败,学号或密码错误", Toast.LENGTH_LONG).show();            }else{//登陆成功                //保存用户名密码在 sharedpreference                SharedPreferences.Editor editor = getSharedPreferences(                        ConstVal.USER_SHARE_PREFERENCE, MODE_PRIVATE).edit();                if(savePassCkb.isChecked()){                    editor.putString("username", username);                    editor.putString("password", password);                }else{                    //editor.putString("username", "");                    editor.putString("password", "");                }                editor.putBoolean("isChecked",savePassCkb.isChecked());                editor.commit();                Toast.makeText(LoginActivity.this, "登陆成功",                        Toast.LENGTH_SHORT).show();                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);                startActivity(intent);                finish();            }        }    }

Executions of AsyncTask class from main thread:

Here is the Syntax for execution of AsyncTasks classs.

LoginAsyncTask task = new LoginAsyncTask(username, password);task.execute();

AsyncTask’s generic types In Android:

The three types used by Asynchronous task are the following:

AsyncTask <TypeOfVarArgParams, ProgressValue, ResultValue>

1. TypeOfVarArgParams: Params is the type of the parameters sent to the task upon execution.
2. ProgressValue: Progress is the type of the progress units published during the background computation.
3. ResultValue: ResultValue is the type of the result of the background computation.


Method of AsyncTask In Android:

In Android, AsyncTask is executed and goes through four different steps or method. Here are these four methods of AsyncTasks.

1. onPreExecute() – It invoked on the main UI thread before the task is executed. This method is mainly used to setup the task for instance by showing a ProgressBar or ProgressDialog in the UI(user interface).

2. 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. The result of the operations must be returned by this step and it will be passed back to the last step/method i.e onPostExecutes(). This method can also use publishProgress(Progress…) to publish one or more units of progress. These values will be published on the main UI thread in the onProgressUpdate(Progress…) method.

3. onProgressUpdate(Progress…) – This method is invoked on the main UI thread after a call to publishProgress(Progress…). Timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background operations are executing. We can also update our progress status for good user experience.

4. onPostExecute(Result) – This method is invoked on the main UI thread after the background operation finishes in the doInBackground method. The result of the background operation is passed to this step as a parameter and then we can easily update our UI to show the results.


Rules of AsyncTask:

There are a few threading rules that must be followed for this class to work properly:

1. This class must be loaded on the UI thread. This is done automatically as from JELLY_BEAN.
2. The task instance must be created on the UI thread.
3. execute(Params…) method that executes it, must be invoked on the UI thread.
4. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params…), onProgressUpdate(Progress…) manually, just executes the class and then will call automatically for good user experience.

参考于:https://abhiandroid.com/programming/asynctask

 

更多相关文章

  1. 【Android】入门案例(二)——JDBC连接MySql数据库实现登录
  2. Android(安卓)SDK Manager 更新失败的解决方法
  3. Android(安卓)Studio 的 gradle 插件升级失败
  4. android 安卓事件处理示例
  5. 基于ANDROID的网上订餐系统
  6. Android兼容性问题 -- WebP格式图片解码失败
  7. 登录时旋转等待效果
  8. Android(安卓)简单的账号密码登陆界面(IO流)
  9. Android通知栏消息(基本文字通知)

随机推荐

  1. Android(安卓)Run ERROR: Unknown option
  2. Android(安卓)和 H5 互调
  3. 2011.10.13(4)——— android android:layo
  4. Android中自定义水平的ProgressBar
  5. 程序小白----AndroidStudio之飞机大战
  6. Android中照相机的使用
  7. Android(安卓)4.0 ICS SystemUI浅析——S
  8. 仿微信摇一摇功能,android 重力感应开发
  9. eclipse下载androidSDK
  10. Android(安卓)中RxPermissions 的使用