AsyncTask 和 Handler

来源:互联网 发布:网络销售代理合同范本 编辑:程序博客网 时间:2024/06/05 19:19

一、AsyncTask和Handler的初步了解

    1.AsyncTask的初识

         介绍:http://blog.sina.com.cn/s/blog_8417aea80100t6y2.html

         使用实例:http://blog.csdn.net/qianfu111/article/details/10200105

            附上使用实例中的代码

             MainActivity:

               

package com.example.mygeneralutil;import java.net.URI;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.os.AsyncTask;import android.os.Bundle;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.util.Log;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;import android.widget.Toast;public class MainActivity extends Activity {private Button mDownloadBtn;private Button mCancelBtn;private ImageView mImage1;private ImageView mImage2;private ProgressBar mProgress1;private ProgressBar mProgress2;private GetLogoFromInternet mTask;private String TAG = "GetLogoFromInternet";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.asynctask_activity);initComponent();}private void initComponent() {mDownloadBtn = (Button) findViewById(R.id.button1);mDownloadBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {mTask = new GetLogoFromInternet();mTask.execute("http://d.hiphotos.baidu.com/album/w%3D2048/sign=6b4e0cbb023b5bb5bed727fe02ebd439/7dd98d1001e939016245802e7aec54e736d1965e.jpg","http://a.hiphotos.baidu.com/album/w%3D2048/sign=4a44fc70342ac65c67056173cfcab311/b8389b504fc2d562f5f6f0fde61190ef76c66c27.jpg");}});mCancelBtn = (Button) findViewById(R.id.button2);mCancelBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubmTask.cancel(true);}});mImage1 = (ImageView) findViewById(R.id.imageView1);mImage2 = (ImageView) findViewById(R.id.imageView2);mProgress1 = (ProgressBar) findViewById(R.id.progressBar1);mProgress2 = (ProgressBar) findViewById(R.id.progressBar2);}@Overridepublic 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;}class GetLogoFromInternet extends AsyncTask<String, Integer, Bitmap> {private Bitmap bitmap = null;@Overrideprotected void onPreExecute() {mImage1.setImageBitmap(null);mImage2.setImageBitmap(null);mProgress1.setProgress(0);mProgress2.setProgress(0);Log.e(TAG, "onPreExecute");}@Overrideprotected Bitmap doInBackground(String... params) {publishProgress(0, 0);HttpClient hc = new DefaultHttpClient();publishProgress(30, 0);HttpGet hg = new HttpGet();Bitmap bitmap2 = null;try {hg.setURI(new URI(params[0]));HttpResponse response = hc.execute(hg);bitmap = BitmapFactory.decodeStream(response.getEntity().getContent());publishProgress(100, 30);hg.setURI(new URI(params[1]));HttpResponse response2 = hc.execute(hg);bitmap2 = BitmapFactory.decodeStream(response2.getEntity().getContent());} catch (Exception e) {Log.e(TAG, "" + e.getMessage());}publishProgress(100, 100);Log.e(TAG, "doInBackground");// mImage1.setImageBitmap(bitmap);//errorreturn bitmap2;}@Overrideprotected void onProgressUpdate(Integer... values) {mProgress1.setProgress(values[0]);mProgress2.setProgress(values[1]);Log.e(TAG, "onProgressUpdate");}@Overrideprotected void onPostExecute(Bitmap result) {if (result != null) {mImage1.setImageBitmap(bitmap);mImage2.setImageBitmap(result);Toast.makeText(MainActivity.this,"get image from network successful", Toast.LENGTH_SHORT).show();} else {Toast.makeText(MainActivity.this,"get image from network error", Toast.LENGTH_SHORT).show();}Log.e(TAG, "onPostExecute");}@Overrideprotected void onCancelled() {mProgress1.setProgress(0);mProgress2.setProgress(0);Log.e(TAG, "onCancelled");}}}
    

         布局文件:

          

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#ffffff"    android:orientation="vertical" >    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:padding="10dp" >        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:gravity="center"            android:orientation="vertical" >            <ProgressBar                android:id="@+id/progressBar1"                style="?android:attr/progressBarStyleHorizontal"                android:layout_width="match_parent"                android:layout_height="wrap_content" />            <ImageView                android:id="@+id/imageView1"                android:layout_width="150dp"                android:layout_height="150dp" />            <ProgressBar                android:id="@+id/progressBar2"                style="?android:attr/progressBarStyleHorizontal"                android:layout_width="match_parent"                android:layout_height="wrap_content" />            <ImageView                android:id="@+id/imageView2"                android:layout_width="150dp"                android:layout_height="150dp" />            <Button                android:id="@+id/button1"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:text="download image" />            <Button                android:id="@+id/button2"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:text="cancel download image" />        </LinearLayout>    </ScrollView></LinearLayout>

    2.Handler的初识

      介绍:主要接受子线程发送的数据, 并用此数据配合主线程更新UI. 

     用法:之前曾使用过

 

二、AsyncTask 和 Handler的异同点

     http://blog.sina.com.cn/s/blog_8417aea80100t6y2.html

     http://blog.csdn.net/onlyonecoder/article/details/8484200

0 0
原创粉丝点击