4.5.3 Async耗时操作必须由子线程完成,更新UI需要由主线程完成

1:异步任务。主要是用来网络访问的。用来访问网络的。用来访问网络的。用来访问网络的。用来访问网络的。
asyncTask


程序超过5秒没有响应,就认为是耗时操作,程序会出现ANR
Application Not Response(应用程序无响应)


+++++++++++++++++++++++++++++++++++++
总结:+++++++++++++++++++++++++++++++++++++
耗时操作必须由子线程完成,+++++++++++++++++++++++++++++++++++++
耗时操作必须由子线程完成,更新UI需要由主线程完成。++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++


doInBackground 里面由子线程来执行,耗时操作写在该方法中
onPostExecute 该方法由UI线程执行。
类中的泛型:
第一个泛型是doInBackground方法参数的类型


第三个参数是doInBackground方法返回值的类型。
先执行doInBackground 方法,然后执行onPostExecute方法。
比如说从网获取一张图片,你要获取了才能显示到上面去。




        for(int i=10;i>0;i--){
        new DaoJiShi2().execute(""+i);
        }


    class DaoJiShi2 extends AsyncTask<String, Void,String>{
protected String doInBackground(String... arg) {

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return arg[0];
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
textview.setText(result);
}
    }




2:ProgressBar的style
<ProgressBar 
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal"
        />


3:Bitmap  bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);


class DownImage extends AsyncTask<String,Void,Bitmap>
{   String url = null;
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap =  null;
if(params!=null)
url = params[0];
HttpGet get = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
try {
response = client.execute(get);
if(response.getStatusLine().getStatusCode()==200)
{  //使用EntityUtils把服务器端返回的数据转成字节数组
byte[] data = EntityUtils.toByteArray(response.getEntity());++++++++++++++++++++++++
bitmap = BitmapFactory.decodeByteArray(data,0, data.length);++++++++++++++++++++++++
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值