onPreExecute():我们主线程使用了.execute方法后,会直接启动执行onPreExecute方法(运行在UI线程上)。
doInBackground(Params…):执行完onPreExecute后,立即在后台线程运行,此步骤可能需要长时间的后台计算。execute()方法中的参数也被传到这步。计算结果必须由这步骤返回,并返回到最后一步(也就是onPostExecute方法)。这一步骤也可以使用publishprogress发布任务的进度,进度会被发送到onProgressUpdata。
onProgressUpdate(Progress…):在这个线程中使用的publishprogress方法中的参数会直接传到onProgressUpdata方法中。onProgressUpdate(Progress…)调用publishprogress后,执行该步骤(运行在UI线程),执行时间是不确定的。这个方法用于在后台计算仍在执行时在用户界面显示进度。例如:用一个进度条显示下载视频的百分比。
onPostExecute(Result):后台计算(doInBackground方法)完成时,会返回一个值。在UI线程运行该方法。后台计算结果作为一个参数传递到这步。我们在此方法中可以根据返回的值来判断操作执行成功或者是失败。
public class Main4Activity extends AppCompatActivity {
private TextView textView;
private ProgressDialog progressDialog;
private int t = 0;
private int f = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
textView = (TextView) findViewById(R.id.main_TV);
MyTask myTask = new MyTask(this);
myTask.execute();
}
private class MyTask extends AsyncTask<String, Integer, Integer>
{
private Context context;
MyTask(Context context){
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
///UI线程执行, 运行在UI线程中,在调用doInBackground()之前执行
progressDialog = new ProgressDialog(Main4Activity.this);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("trest");
progressDialog.show();
textView.setText("onPreExecute");
Toast.makeText(context,"开始执行",Toast.LENGTH_SHORT).show();
}
@Override
protected Integer doInBackground(String... params)
{
///后台运行的方法,可以运行非UI线程,可以执行耗时的方法
// System.out.println(params[0]);
int i = 0;
while (i <100) {
i++;
publishProgress(i);
try {
Thread.sleep(100);
} catch (Exception e) {
return f;
}
}
return t;
}
@Override
protected void onProgressUpdate(Integer... value) {
//在publishProgress()被调用以后执行,publishProgress()用于更新进度
//super.onProgressUpdate(value);
progressDialog.setProgress(value[0]);
textView.setText("onProgressUpdate"+value[0]);
}
@Override
protected void onPostExecute(Integer result) {
///运行在ui线程中,在doInBackground()执行完毕后执行
//super.onPostExecute(result);
progressDialog.dismiss();
textView.setText("onPostExecute"+result);
if (result == t){
Toast.makeText(context,"执行完毕==成功",Toast.LENGTH_SHORT).show();
}else if(result == f) {
Toast.makeText(context,"执行完毕==失败",Toast.LENGTH_SHORT).show();
}
}
}
}
布局文件就是一个TestView其他没什么。。我们这个主要就是在主线程不进行耗时操作,只在子线程进程操作,并且在子线程执行耗时操作的同时,能将数据传给主线程,而主线程就是显示一个弹出框,表示正在进行耗时操作,子线程耗时操作执行完毕之后,弹出框自动消失。。。。。。