AsyncTask是安卓提供的一个异步请求方法,在安卓中,一些耗时操作比如数据处理,网络请求等都需要放在异步线程中执行,这样可以优化UI主线程的卡顿。
public class Net_AsyncTask extends AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Object doInBackground(Object[] objects) {
return null;
}
@Override
protected void onProgressUpdate(Object[] values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
上面是一个完整的AsyncTask模块,提供了四个方法,onPreExecute,doInBackground,onProgressUpdate,onPostExecute
执行顺序为: onPreExecute–>doInBackground–>onProgressUpdate–>onPostExecute
1、onPreExecute:这是一个预处理方法,在任务开始的时候执行,我们可以在这里进行一些控件的实例化,设置属性等。
2、doInBackground:这是一个任务操作方法,也是最重要的一个方法,所有的耗时操作都应该在这里执行。
3、onProgressUpdate:这是一个进度即时更新方法,在这里我们可以即时更新任务滚动条的进度。
4、onPostExecute:这是一个任务结果处理方法,在doInBackground里执行完任务,会将结果通知给这个类,在这类中我们可以对UI进行更新操作
上面的1、3、4是UI主线程触发调用的,所以可以对UI进行更新操作,而第2步是个异步操作,不能在里面进行UI的更新操作。
在实际使用中,我们大多数只会用到2,4两个方法,调用AsyncTask执行耗时操作,完成后刷新界面
下面在前几章登录注册模块中继续开发:
第一步 在manifest文件中添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
第二步 在gradle文件中添加okhttp3的依赖,okhttp3是一个安卓常用网络请求框架
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
第三步 修改Net_AsyncTask如下
import android.app.Activity;
import android.os.AsyncTask;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Net_AsyncTask extends AsyncTask {
public String username = "";
public String password = "";
public Boolean is_login = false;
public OnInteraction listenser = null;
public void Net_AsyncTask(String username,String password){
this.username = username;
this.password = password;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Object doInBackground(Object[] objects) {
OkHttpClient client = new OkHttpClient();
FormBody.Builder formBody = new FormBody.Builder();
formBody.add("username",username);
formBody.add("password",password);
Request request = new Request.Builder()
.url("your url")
.post(formBody.build())
.build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
if (response != null && response.isSuccessful()) {
String result = response.body().toString();
if (result.equals("success")){
is_login = true;
}
}
return null;
}
@Override
protected void onProgressUpdate(Object[] values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
if (listenser != null){
listenser.Net_AsyncTask_OnInteraction(is_login);
}
}
public interface OnInteraction{
public void Net_AsyncTask_OnInteraction(Boolean is_login);
}
public void setListener(Activity activity){
listenser = (OnInteraction)activity;
}
}
第四步 在MainActivity中调用,注意login按钮点击处方法修改
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import inforcreation.com.myapplication.Task.Net_AsyncTask;
import inforcreation.com.myapplication.Util.SharePreferenceUtil;
public class MainActivity extends AppCompatActivity implements View.OnClickListener,Net_AsyncTask.OnInteraction{
private Button log_in = null;
private Button register = null;
private EditText user_name = null;
private EditText password = null;
public String user_name_temp = "username";
public String password_temp = "123456";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (SharePreferenceUtil.get(getApplicationContext())){
Login();
finish();
return;
}else {
setContentView(R.layout.activity_main);
init();
}
}
public void init(){
log_in = (Button)findViewById(R.id.log_in);
register = (Button)findViewById(R.id.register);
user_name = (EditText)findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.password);
log_in.setOnClickListener(this);
register.setOnClickListener(this);
}
public void Login(){
Intent intent = new Intent(MainActivity.this,LoginSuccessActivity.class);
startActivity(intent);
}
@Override
public void onClick(View v) {
if (v == log_in){
String str_1 = user_name.getText().toString();
String str_2 = password.getText().toString();
if (str_1 == null || str_1.isEmpty() || str_2 == null || str_2.isEmpty() ){
Toast.makeText(this,"用户名密码错误",Toast.LENGTH_SHORT).show();
return;
}
if ((str_1.equals(user_name_temp) && str_2.equals(password_temp)) || ( SharePreferenceUtil.new_user_compare(getApplicationContext(),str_1,str_2))){
Net_AsyncTask net_asyncTask = new Net_AsyncTask(str_1,str_2);
net_asyncTask.setListener(this);
net_asyncTask.execute();
}else {
Toast.makeText(this,"用户名密码错误",Toast.LENGTH_SHORT).show();
}
}else if (v == register){
String str_1 = user_name.getText().toString();
String str_2 = password.getText().toString();
if (str_1 == null || str_1.isEmpty() || str_2 == null || str_2.isEmpty()){
Toast.makeText(this,"用户名密码错误",Toast.LENGTH_SHORT).show();
return;
}
SharePreferenceUtil.register(getApplicationContext(),str_1,str_2);
Toast.makeText(this,"新用户注册成功",Toast.LENGTH_SHORT).show();
}
}
@Override
public void Net_AsyncTask_OnInteraction(Boolean is_login) {
if (is_login){
SharePreferenceUtil.commit(getApplicationContext(),true);
Login();
finish();
}else {
Toast.makeText(this,"登录失败",Toast.LENGTH_SHORT).show();
}
}
}
至此,我们便完成了登录模块异步请求服务器功能,同理,注册功能也能修改为异步请求。