1、使用新线程的原因:
android的UI线程主要负责处理用户的按键事件、用户触屏事件及屏幕绘图事件,因此其它其它操作不应该、也不能阻止UI线程,否则UI界面将会变得停止响应。
2、解决新线程不能更新UI组件的问题
2.1、使用Handler实现线程通信
2.2、Activity.runOnUiThread(Runnable)
2.3、View.post(Runnable)
2.4、View.postDelayed(Runnable)
2.5、AsyncTask
3、AsyncTask的使用:AsyncTask<Params,Progress,Result>是一个抽象类,通常用于被继承
3.1、参数介绍:Params,启动任务执行输入参数的类型,Progress后台任务完成的进度值的类型,Result后台完成后返回结果的类型
3.2、方法介绍:
3.2.1、AsyncTask.cancel(boolean)如果是true,如果线程执行,则会被打断,如果是false,线程将会被运行执行完成
3.2.2、onPreExecute()//一般用来做一些初始化操作
3.2.3、doInBackground(String... strings)//处理后台线程要完成的任务
3.2.4、onProgressUpdate(Integer ... values)
//在doInBackgrounp()方法中调用 publishProgress(Progress... values)方法更新任务执行的进度,将会触发该方法
3.2.5、onPostExecute(Integer result)//doInBackGrounp()完成后自动调用此方法,用来处理结果
new AsyncTask<String,Void,Integer>(){//如果为泛型参数,就设为void
protected void onPreExecute() {}
//处理后台线程要完成的任务
protected Integer doInBackground(String... strings) {
//strings[0]=account strings[1]=pwd
return loginCode;
}
protected void onProgressUpdate(Integer ... values){}
//doInBackGrounp()完成后自动调用此方法,用来处理结果
protected void onPostExecute(Integer result) {}
}.execute(account,pwd,host);
3.3、超时处理
private Handler uiHandler = new Handler(){
public void handleMessage(Message msg) {
switch(msg.what){
case cancelMyTask:
if(myTask!=null && !myTask.isCancelled()
&& myTask.getStatus() == AsyncTask.Status.RUNNING){
myTask.cancel(true);
myTask = null;
showLayout.setVisibility(View.GONE);
MyToast.showToastLong(context, "连接超时");
}
break;
}
}
};
final MyTask myTask = new MyTask();//继承AsyncTask
//只是打断AsyncTask,并没有结束掉myTask.cancel(true);
myTask.execute(account,pwd,host);
Thread thread = new Thread(){
public void run(){
try{
myTask.get(5000, TimeUnit.MILLISECONDS);
}catch(InterruptedException e){
}catch(ExecutionException e){
}catch(TimeoutException e){
uiHandler.sendEmptyMessage(cancelMyTask);;
}
}
};