[Android] AsyncTask的使用

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;
        private final String mPassword;

        public int login_ret = 0;

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            login_ret = GBase.userLogin(mEmail,mPassword);

            return  true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            switch (login_ret){
                case 0:
                    startActivity(new Intent(LoginActivity.this,MainActivity.class));
                    finish();
                    break;
                case -1:
                    mEmailView.setError(getString(R.string.error_invalid_email));
                    mEmailView.requestFocus();
                    break;
                case -2:
                    mPasswordView.setError(getString(R.string.error_incorrect_password));
                    mPasswordView.requestFocus();
                    break;
                case -3:
                    break;
                default:break;
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

负责后台处理的任务:
Boolean doInBackground(Void… params);
当后台任务处理完成后,会执行:
onPostExecute(final Boolean success);
其中Boolean doInBackground(Void… params)的返回值作为onPostExecute(final Boolean success)的输入参数。
执行代码:

    private UserLoginTask mAuthTask = null;
    mAuthTask = new UserLoginTask(email, password);
    //执行该任务
    mAuthTask.execute((Void) null);
    //取消该任务
    //mAuthTask.cancel(true);

你可能感兴趣的:(android)