现在的位置: 首页 > 综合 > 正文

Android AsyncTask Demo异步下载

2018年01月31日 ⁄ 综合 ⁄ 共 2261字 ⁄ 字号 评论关闭

Android子线程不允许更改UI,为此有几种解决方案,其中比较简单的有Handler和AsyncTask,以下是异步下载图片更新UI的Demo

public class MainActivity extends Activity {
	ImageView show;
	Button load;
	ProgressDialog dialog;
	String path="http://avatar.csdn.net/D/8/8/1_bttiyotogmail.jpg";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		show=(ImageView)findViewById(R.id.show);
		load=(Button)findViewById(R.id.load);
		dialog=new ProgressDialog(this);
		dialog.setTitle("下载");
		dialog.setMessage("正在下载...");
		//设置ProgressDialog的样式为水平
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		
		
		load.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				new MyTask().execute(path);
				
			}
		});

	}
	
		//	   Params 启动任务执行的输入参数,比如HTTP请求的URL。 
		//	  Progress 后台任务执行的百分比。 
		//	  Result 后台执行任务最终返回的结果,比如String,Bitmap
	public class MyTask extends AsyncTask<String, Integer, Bitmap>{

		@Override//实际下载任务
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap=null;
			InputStream inputStream = null;
			ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
			try {
				HttpClient client=new DefaultHttpClient();
				HttpGet get=new HttpGet(params[0]);
				HttpResponse response=client.execute(get);
				Log.e("Tag", "!!!");
				if (response.getStatusLine().getStatusCode()==200) {
					inputStream=response.getEntity().getContent();
					long length = response.getEntity().getContentLength();
					byte[] data =new byte [1024];
					int temp=0;
					int total_length = 0;
					while((temp=inputStream.read(data))!=-1){
						total_length+=temp;
						int value = (int)((total_length/(float)length)*100);
						publishProgress(value);
						outputStream.write(data,0,temp);
						
					}
					byte[] result= outputStream.toByteArray();
					bitmap=BitmapFactory.decodeByteArray(result, 0, result.length);
				}
				
				
				
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}finally{
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			return bitmap;
			
		}

		@Override//下载结束
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			show.setImageBitmap(result);
			Log.e("Tag", "Over!!!");
		}

		@Override//下载更新
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			dialog.setProgress(values[0]);
			
		}

		@Override//显示进度条
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog.show();
		}

		
	}

}

抱歉!评论已关闭.