AsyncTask //翻译加实例 未完
2014-03-21 17:14
211 查看
AsyncTask
类概述:AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
//异步任务能够适当和容易的使用主线程。这个类允许执行后台的任务并且在主线程上面宣告结果,在这个过程中不需要使用线程和handlers.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods
of time, it is highly recommended you use the various APIs provided by the java.util.concurrent (并发)pacakge such as Executor(执行者), ThreadPoolExecutor and FutureTask.
//AsyncTask被设计作为对Thread和Handler的一个帮助类,使用时不需要建立一般的线程框架。理想的情况下,AsyncTask被用来执行
短时间的操作(最多几秒钟).如果你需要让线程保持一个较长时间的工作,强烈推荐你使用java.util.concurrent包提供的各种各样的API,例如Excutor,ThreadPoolExecutor和FutureTask。
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground,
onProgressUpdate and onPostExecute.
//在后台线程里面执行运算并且将结果显示在主线程里面的过程被定义为一个异步任务。一个异步任务通过三个通用的类型(Params,Progress,Result)和四个步骤(onPreExcute,doInBackground,onProgressUpdate,和onPostExcute)被定义。
开发者指南:
For more information about using tasks and threads, read the Processes and Threads developer guide.
//更多的关于任务和线程的信息,参考开发者指南里面的"Progres and Threads "一文。
//Usage用法
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
//AsyncTask必须被继承使用.子类必须重写至少一个方法(doInBackground(Params...)),大多数情况下也会重写第二个方法(onPostExcute(Result)).
package com.cdc.asynctaskdemo; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; public class MainActivity extends Activity { private Button bt; /** 进度条 **/ private ProgressBar pb; private Bitmap bitmap; private ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt = (Button) findViewById(R.id.bt1); iv = (ImageView) findViewById(R.id.iv1); pb = (ProgressBar) findViewById(R.id.pb1); bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub AsyncImage asyncImage = new AsyncImage(); asyncImage.execute("http://y3.ifengimg.com/a39fc0c47ae80a31/2014/0321/rdn_532bd2fd87276.jpg"); } }); } @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; } private final class AsyncImage extends AsyncTask<String, Integer, Bitmap> { @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); pb.setVisibility(View.VISIBLE); } //后台进程获取图片 @Override protected Bitmap doInBackground(String... params) { // TODO Auto-generated method stub try { URL url = new URL(params[0]); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); int len = conn.getContentLength(); pb.setMax(len); InputStream in = null; for (int i = 1; i <= len; i = i * 2) { in = conn.getInputStream(); publishProgress(i); } bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bitmap; } /** 在主线程更新UI **/ @Override protected void onPostExecute(Bitmap result) { // TODO Auto-generated method stub super.onPostExecute(result); //显示图片 iv.setImageBitmap(result); pb.setVisibility(View.GONE); } /**** 更新进度条 **/ @Override protected void onProgressUpdate(Integer... values) { // TODO Auto-generated method stub super.onProgressUpdate(values); pb.setProgress(values[0]); } } }
布局文件:
<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" > <Button android:id="@+id/bt1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/bt1" /> <ProgressBar android:id="@+id/pb1" android:layout_width="match_parent" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal" android:visibility="invisible" android:layout_below="@id/bt1" /> <ImageView android:id="@+id/iv1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/bt1" android:contentDescription="@string/bt1" > </ImageView> </RelativeLayout>
相关文章推荐
- 【翻译自mos文章】rac数据库中,HC_<SID>.dat文件被其他Oracle_Home下的实例所使用。
- SQL Server 2005 默认实例和命名实例(这文章翻译得真绕嘴)
- Python3.2官方文档翻译--实例对象和方法对象
- 星火杯项目笔记——iOS调用有道API翻译句子、在AppDelegate里实现全局访问的sqlite实例【13-10-14】
- [翻译]ActionScript 3 Jpeg Encoder实例:保存flash中的图片 - [flash开发]
- RPL(4):RFC6550翻译(4)---RPL的通信流支持&RPL实例
- 微信公众帐号开发教程第17篇-应用实例之智能翻译
- 【翻译】WF从入门到精通(第三章):workflow实例
- [041] 微信公众帐号开发教程第17篇-应用实例之智能翻译
- 微信公众帐号开发教程第17篇-应用实例之智能翻译
- [041] 微信公众帐号开发教程第17篇-应用实例之智能翻译
- 在EntityFramework6中管理DbContext的正确方式——4DbContextScope:一个简单的,正确的并且灵活的管理DbContext实例的方式(外文翻译)
- 【翻译自mos文章】设置了RemoveIPC=yes 的RHEL7.2 会crash掉Oracle asm 实例和Oracle database实例
- .NET调试实例-实验1:死锁 - 回顾 (原创翻译)
- jQuery中文入门指南,翻译加实例,jQuery的起点教程
- jQuery中文入门指南,翻译加实例,jQuery的起点教程
- java 理解实例和类成员(翻译自Java Tutorials)
- 微信公众帐号开发教程第17篇-应用实例之智能翻译
- Arduino 扩展库的制作(官网原文件精细翻译)--附详细实例教程
- JSF+Spring+Hibernate的实例讲解(原创翻译)