[Android] AsyncTask的使用
16lz
2021-12-04
/** * 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与服务器通信
- Android/Bluetooth 初始化流程
- android欢迎界面并执行任务
- Android(安卓)RatingBar案例
- Android(安卓)通信录中的联系人操作
- Android应用中使用Popupmenu
- android
- android执行外部程序,类似DELPHI里的EXEC函数
- Android(安卓)轮询实现的三种方式