android 开发-AsyncTask异步任务的实现
- AsyncTask实现的原理,和适用的优缺点
AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主线程.
以下部分是学习代码:
UI:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="750dp"
android:maxHeight="400dp"
android:adjustViewBounds="true"
/> <Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="68dp"
android:text="下载网络图片" /> </RelativeLayout>
Activity:
package com.example.android_asynctask_downloadimage; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView; /**
* @author xiaowu
* NOTE:异步任务AsyncTask
*/
public class MainActivity extends Activity {
private Button button ;
private Button button2 ;
private ImageView imageView ;
private final String IMAGE_PATH ="http://e.hiphotos.baidu.com/zhidao/pic/item/c2fdfc039245d68858f1c69fa5c27d1ed21b241d.jpg";
private ProgressDialog progressDialog ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) this.findViewById(R.id.button1);
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("提示");
// progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("正在下载图片,请耐心等待..."); imageView = (ImageView) this.findViewById(R.id.imageView1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new MyTask().execute(IMAGE_PATH);
}
}); }
/**
* @author xiaowu
* 异步任务AsyncTask,执行网络下载图片
* AsyncTask<String, Integer, byte[]> 如果异步任务不需要参数传递,可以直接将参数设置为Void
* params:
* String:(网络图片的)路径
* Integer: 进度单位,刻度类型
* byte[]:异步任务执行的返回结果
* 异步任务有4个步骤:
* 1、onPreExecute(); 在异步任务执行之前执行,用来构建一个异步任务,如显示一个进度条给用户看
* 2、doInBackground(Params...); 异步任务必须实现的方法,具体的异步任务所做的事情
* 3、onProgressUpdate(Progress...);
* 4、onPostExecute(Result);
*/
public class MyTask extends AsyncTask<String, Integer, byte[]>{
//在异步任务执行之前执行,用来构建一个异步任务,如显示一个进度条给用户看
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//展示进度条对话框
progressDialog.show();
}
//异步任务必须实现的方法,具体的异步任务所做的事情。并将结果返回值最后一个步骤。
@Override
protected byte[] doInBackground(String... params) {
// TODO Auto-generated method stub
//
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
InputStream inputStream = null;
byte[] result = null; //图片的所有内容
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
//发起get请求,并获取反馈
HttpResponse httpResponse = httpClient.execute(httpGet);
long file_length = httpResponse.getEntity().getContentLength(); //文件实际总长度
int total_length = 0 ;
byte[] data = new byte[1024];
int len = 0 ;
if (httpResponse.getStatusLine().getStatusCode()==200) {
// result = EntityUtils.toByteArray(httpResponse.getEntity());
//读取返回内容(内容是以流的形式返回)
inputStream = httpResponse.getEntity().getContent();
//更新进度条并读取数据
while ((len = inputStream.read(data)) != -1) {
total_length +=len ;
int progress_value = (int) ((total_length/ (float) file_length)*100);
//通过publishProgress()方法发布进度值到onProgressUpdate
publishProgress(progress_value); //发布刻度单位
byteArrayOutputStream.write(data, 0, len);
}
}
result = byteArrayOutputStream.toByteArray();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关连接
httpClient.getConnectionManager().shutdown();
} return result;
}
//更新UI展示信息:如进度条的变动
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
progressDialog.setProgress(values[0]);
}
//将doInBackground的执行结果展示到UI
@Override
protected void onPostExecute(byte[] result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
imageView.setImageBitmap(bitmap);
progressDialog.dismiss();
} }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} }
android 开发-AsyncTask异步任务的实现的更多相关文章
- Android开发之异步具体解释(二)之AsyncTask
请尊重他人的劳动成果,转载请注明出处:Android开发之异步具体解释(二)之AsyncTask http://blog.csdn.net/fengyuzhengfan/article/details ...
- Android 多线程----AsyncTask异步任务详解
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/3 ...
- Android开发——AsyncTask详解
android提供AsynvTask,目的是为了不阻塞主线程(UI线程),且UI的更新只能在主线程中完成,因此异步处理是不可避免的. Android为了降低开发难度,提供了AsyncTask.Asyn ...
- Android中AsyncTask异步
今天我们学习了 AsyncTack, 这是一个异步任务. 那么这个异步任务可以干什么呢? 因为只有UI线程,即主线程可以对控件进行更新操作.好处是保证UI稳定性,避免多线程对UI同时操作. 同时要把耗 ...
- Android使用AsyncTask异步线程网络通信获取数据(get json)
摘要: android 4.0以上强制要求不能在主线程执行耗时的网络操作,网络操作需要使用Thead+Handler或AsyncTask,本文将介绍AsyncTask的使用方法. 内容: 1.添加Ht ...
- Android 利用 AsyncTask 异步读取网络图片
1.新建Android工程AsyncLoadPicture 新建布局文件activity_main.xml主界面为一个GridView,还有其子项布局文件gridview_item.xml 2.功能主 ...
- Android开发之异步消息处理机制Handler
更加详细的介绍Handler的博文-http://blog.csdn.net/guolin_blog/article/details/9991569 Android中的异步消息处理主要有四个部分组成, ...
- Android开发之异步消息处理机制AsyncTask
转自:Android AsyncTask完全解析,带你从源码的角度彻底理解 另外一篇比较详细的博文:http://blog.csdn.net/liuhe688/article/details/6532 ...
- Android开发之异步获取并下载网络资源-下载图片和下载文本内容
在android网络开发过程中,经常需要获取网络资源,比如下载图片,下载文本文件内容等,这个时候就需要http请求来获取相应的网络资源.首先看看实例效果图: 下载图片截图 ...
随机推荐
- C#图片压缩类winform
using System;using System.Collections.Generic;using System.Text;using System.Drawing;using System.Dr ...
- js比较日期字串的大小
function checkTime() { var startTime = $('#startTime').val(); var endTime = $('#endTime').val(); if( ...
- 各种浏览器下的user-agent
ie11Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko safariMozilla/5.0 (Macintos ...
- ubuntu下root用户默认密码及修改方法
[ubuntu下root用户默认密码及修改方法] 很多朋友用ubuntu,一般都是装完ubuntu系统,马上就修改root密码了,那么root用户的默认密码是多少,当忘记root用户密码时如何找回呢, ...
- hadoop2.6.0完全分布式部署
这里是hadoop最小的配置,也就是修改最少量的东西让hadoop跑起来. 系统是 Centos6.7 64位, hadoop是2.6.0,虚拟机是VMWare WorkStation 假设虚拟机启动 ...
- Struts学习总结 学习
ContextMap 包含值栈包含 root(list结构)和context(map结构) 值栈包含contextMap的引用. Actioncontext是工具类 可以获取他们 Struts2拥 ...
- 22. CTF综合靶机渗透(十五)
靶机说明: Game of Thrones Hacking CTF This is a challenge-game to measure your hacking skills. Set in Ga ...
- 3. 文件上传靶机实战(附靶机跟writeup)
upload-labs 一个帮你总结所有类型的上传漏洞的靶场 文件上传靶机下载地址:https://github.com/c0ny1/upload-labs 运行环境 操作系统:推荐windows ...
- Access denied for user 'xxx'@'localhost' 问题的解决方法
使用SpringMvc + Mybatis + Mysql搭建的架构,调试时出现了以下错误: HTTP Status 500 - Request processing failed; nested e ...
- 20169219《linux内核原理与分析》第七周作业
网易云课堂学习 把write系统调用加入到MenuOS里面 我在试验过程中在MenuOS里加入了time.time-asm.write和write-asm命令.以time和time-asm为例, 步骤 ...