Handler和AsyncTask的⼩实验
写了⾃⼰的代码, 和原作者的差不多, 条理很清晰。如果读下⾯的代码⽆障碍那么对handler和asynctask的使⽤⾃⼰应该也就会了。上代码,这个最直⽩,哈哈:
1 package com.example.handlertest; 2
3 import org.apache.http.HttpResponse; 4 import org.apache.http.client.HttpClient;
5 import org.apache.http.client.methods.HttpGet;
6 import org.apache.http.impl.client.DefaultHttpClient; 7
8 import android.annotation.SuppressLint; 9 import android.app.Activity;
10 import android.graphics.Bitmap;
11 import android.graphics.BitmapFactory; 12 import android.os.AsyncTask; 13 import android.os.Bundle; 14 import android.os.Handler; 15 import android.os.Message; 16 import android.view.Menu; 17 import android.view.View;
18 import android.view.View.OnClickListener; 19 import android.widget.ImageView; 20 import android.widget.ProgressBar; 21 import android.widget.TextView; 22 import android.widget.Toast; 23
24 public class MainActivity extends Activity implements OnClickListener{ 25
26 TextView tv1; 27 TextView tv2; 28 ImageView iv1; 29 ImageView iv2;
30 ProgressBar progressBar; 31
32 private final static int OK = 0; 33 private final static int BAD = 1; 34
35 private MyHandler myHandler; 36 private Thread thread; 37 @Override
38 protected void onCreate(Bundle savedInstanceState) { 39 super.onCreate(savedInstanceState); 40 setContentView(R.layout.activity_main); 41 init(); 42 43 } 44
45 private void init(){
46 tv1 = (TextView)findViewById(R.id.getpicture); 47 tv2 = (TextView)findViewById(R.id.getsecpicture); 48 iv1 = (ImageView)findViewById(R.id.firstPic); 49 iv2 = (ImageView)findViewById(R.id.secPic);
50 progressBar = (ProgressBar)findViewById(R.id.progressBar); 51
52 tv1.setOnClickListener(this); 53 tv2.setOnClickListener(this); 54
55 myHandler = new MyHandler(); 56 57 }
58 @Override
59 public boolean onCreateOptionsMenu(Menu menu) {
60 // Inflate the menu; this adds items to the action bar if it is present. 61 getMenuInflater().inflate(R.menu.activity_main, menu); 62 return true; 63 }
65 @SuppressLint(\"HandlerLeak\") 66 @Override
67 public void onClick(View arg0) {
68 // TODO Auto-generated method stub 69 if( arg0 == tv1){ 70 if(thread == null){
71 thread = new Thread(runnable); 72 thread.start(); 73 }else{
74 Toast.makeText(getApplication(),
75 getApplication().getString(R.string.ThreadIsOn), Toast.LENGTH_LONG).show(); 76 }
77 }else if(arg0 == tv2){
78 new MyAsyncTask().execute(\"http://csdnimg.cn/www/images/csdnindex_logo.gif\"); 79 } 80 else{ 81 ; 82 } 83 } 84
85 @SuppressLint(\"HandlerLeak\") 86 class MyHandler extends Handler{
87 public void handleMessage(Message msg){ 88 switch(msg.what){ case OK:{
90 Toast.makeText(getApplicationContext(), getString(R.string.ok), Toast.LENGTH_SHORT).show(); 91 iv1.setImageBitmap((Bitmap)msg.obj); 92 }break;
93 case BAD:{
94 Toast.makeText(getApplicationContext(), getString(R.string.bad), Toast.LENGTH_SHORT).show(); 95 }break; 96 default:{ 97 98 }break; 99 }100 }101 }102
103 Runnable runnable = new Runnable() {104 public void run() {
105 HttpClient hc = new DefaultHttpClient();
106 HttpGet hg = new HttpGet(\"http://csdnimg.cn/www/images/csdnindex_logo.gif\");107 Bitmap bm = null;108 try{
109 HttpResponse hr = hc.execute(hg);
110 bm = BitmapFactory.decodeStream(hr.getEntity().getContent());111 }catch(Exception e){
112 myHandler.obtainMessage(BAD).sendToTarget();113 return;114 }
115 myHandler.obtainMessage(OK, bm).sendToTarget();116 }117 };118
119 class MyAsyncTask extends AsyncTask{120121 protected void onPreExecute () {122 iv2.setImageBitmap(null);123 progressBar.setProgress(0);124 }
125 @Override
126 protected Bitmap doInBackground(String... params) {127 // TODO Auto-generated method stub128 publishProgress(20);
129 HttpClient hc = new DefaultHttpClient();
130 HttpGet hg = new HttpGet(\"http://csdnimg.cn/www/images/csdnindex_logo.gif\");131 Bitmap bm = null;132 publishProgress(30);133 try {
134 HttpResponse hr = hc.execute(hg);
135 bm = BitmapFactory.decodeStream(hr.getEntity().getContent()); 136 } catch (Exception e) { 137 return null; 138 }
139 publishProgress(100); 140 return bm;141 }142
143 protected void onProgressUpdate(Integer... progress) {144 progressBar.setProgress(progress[0]);145 }146
147 protected void onPostExecute(Bitmap result) {148 if(result != null) {
149 Toast.makeText(getApplicationContext(), \"成功获取图⽚\150 iv2.setImageBitmap(result); 151 }else {
152 Toast.makeText(getApplicationContext(), \"获取图⽚失败\153 progressBar.setProgress(100);154 }155
156 }157 }158 159 }
下⾯是我的xml主界⾯布局:
1 67 8 android:id=\"@+id/getpicture\" 9 android:clickable=\"true\"10 android:layout_width=\"80dp\"11 android:layout_height=\"80dp\"
12 android:text=\"@string/getPicture\" />13 14 android:id=\"@+id/firstPic\"15 android:contentDescription=\"csdnlogo\"16 android:layout_width=\"wrap_content\"17 android:layout_height=\"wrap_content\"18 android:layout_below=\"@id/getpicture\"/>19 20 android:id=\"@+id/getsecpicture\"21 android:clickable=\"true\"22 android:layout_width=\"80dp\"23 android:layout_height=\"80dp\"
24 android:layout_below=\"@id/firstPic\"25 android:text=\"@string/getPicture\"26 />
27 28 android:id=\"@+id/secPic\"29 android:contentDescription=\"csdnlogo\"30 android:layout_width=\"wrap_content\"31 android:layout_height=\"wrap_content\"
32 android:layout_below=\"@id/getsecpicture\"/>33
34 35 android:layout_below=\"@id/secPic\"36 android:id=\"@+id/progressBar\"37 android:layout_width=\"fill_parent\"38 android:layout_height=\"wrap_content\"
39 style=\"?android:attr/progressBarStyleHorizontal\"/>40
41
记得在manifest⽂件中加上联⽹权限声明: