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.

【Android】AsyncTask 实现登陆_第1张图片


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 Studio 第五十三期 - 自定义EditText密码键盘
  2. Android完美解决输入框EditText隐藏密码打勾显示密码问题
  3. Android Studio在Gradle中隐藏Keystore密码
  4. Android debug.keystore的密码
  5. Android 简单的账号密码登陆界面(IO流)
  6. Android支付密码输入框
  7. Android图案密码,手势锁源码解析
  8. android 更改密码显示风格

随机推荐

  1. Android使用AudioRecord遇到的问题与解决
  2. Android(安卓)ANR问题分析思路
  3. Android(安卓)layout属性大全
  4. 海康威视Android(安卓)SDK,即萤石Android(
  5. android 电容屏(三):驱动调试之驱动程序分析
  6. 简述修改logo以及文字
  7. 关于Android锁屏的问题
  8. android中的数据库操作
  9. Android学习指南基础--第一讲:Android开发
  10. Android