從主執行緒傳送訊息到子執行緒(準確地說應該是非UI執行緒)
package com.zhuozhuo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
public class LooperThreadActivity extends Activity{
/** Called when the activity is first created. */
private final int MSG_HELLO = 0;
private Handler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new CustomThread().start();//新建並啟動CustomThread例項
findViewById(R.id.send_btn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {//點選介面時傳送訊息
String str = "hello";
Log.d("Test", "MainThread is ready to send msg:" + str);
mHandler.obtainMessage(MSG_HELLO, str).sendToTarget();//傳送訊息到CustomThread例項
}
});
}
class CustomThread extends Thread {
@Override
public void run() {
//建立訊息迴圈的步驟
Looper.prepare();//1、初始化Looper
mHandler = new Handler(){//2、繫結handler到CustomThread例項的Looper物件
public void handleMessage (Message msg) {//3、定義處理訊息的方法
switch(msg.what) {
case MSG_HELLO:
Log.d("Test", "CustomThread receive msg:" + (String) msg.obj);
}
}
};
Looper.loop();//4、啟動訊息迴圈
}
}
}
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
public class LooperThreadActivity extends Activity{
/** Called when the activity is first created. */
private final int MSG_HELLO = 0;
private Handler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new CustomThread().start();//新建並啟動CustomThread例項
findViewById(R.id.send_btn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {//點選介面時傳送訊息
String str = "hello";
Log.d("Test", "MainThread is ready to send msg:" + str);
mHandler.obtainMessage(MSG_HELLO, str).sendToTarget();//傳送訊息到CustomThread例項
}
});
}
class CustomThread extends Thread {
@Override
public void run() {
//建立訊息迴圈的步驟
Looper.prepare();//1、初始化Looper
mHandler = new Handler(){//2、繫結handler到CustomThread例項的Looper物件
public void handleMessage (Message msg) {//3、定義處理訊息的方法
switch(msg.what) {
case MSG_HELLO:
Log.d("Test", "CustomThread receive msg:" + (String) msg.obj);
}
}
};
Looper.loop();//4、啟動訊息迴圈
}
}
}
從非UI執行緒傳遞訊息到UI執行緒(介面主執行緒),因為主介面已經有MessageQueue,所以可以直接獲取訊息處理訊息。而上面由主執行緒向非UI執行緒中處理訊息的時候,非UI執行緒需要先新增訊息佇列,然後處理訊息迴圈。
public class ThreadHandlerActivity extends Activity {
/** Called when the activity is first created. */
private static final int MSG_SUCCESS = 0;//獲取圖片成功的標識
private static final int MSG_FAILURE = 1;//獲取圖片失敗的標識
private ImageView mImageView;
private Button mButton;
private Thread mThread;
private Handler mHandler = new Handler() {
public void handleMessage (Message msg) {//此方法在ui執行緒執行
switch(msg.what) {
case MSG_SUCCESS:
mImageView.setImageBitmap((Bitmap) msg.obj);//imageview顯示從網路獲取到的logo
Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_success), Toast.LENGTH_LONG).show();
break;
case MSG_FAILURE:
Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_failure), Toast.LENGTH_LONG).show();
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView= (ImageView) findViewById(R.id.imageView);//顯示圖片的ImageView
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mThread == null) {
mThread = new Thread(runnable);
mThread.start();//執行緒啟動
}
else {
Toast.makeText(getApplication(), getApplication().getString(R.string.thread_started), Toast.LENGTH_LONG).show();
}
}
});
}
Runnable runnable = new Runnable() {
@Override
public void run() {//run()在新的執行緒中執行
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet("http://csdnimg.cn/www/images/csdnindex_logo.gif");//獲取csdn的logo
final Bitmap bm;
try {
HttpResponse hr = hc.execute(hg);
bm = BitmapFactory.decodeStream(hr.getEntity().getContent());
} catch (Exception e) {
mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//獲取圖片失敗
return;
}
mHandler.obtainMessage(MSG_SUCCESS,bm).sendToTarget();//獲取圖片成功,向ui執行緒傳送MSG_SUCCESS標識和bitmap物件
// mImageView.setImageBitmap(bm); //出錯!不能在非ui執行緒操作ui元素
// mImageView.post(new Runnable() {//另外一種更簡潔的傳送訊息給ui執行緒的方法。
//
// @Override
// public void run() {//run()方法會在ui執行緒執行
// mImageView.setImageBitmap(bm);
// }
// });
}
};
/** Called when the activity is first created. */
private static final int MSG_SUCCESS = 0;//獲取圖片成功的標識
private static final int MSG_FAILURE = 1;//獲取圖片失敗的標識
private ImageView mImageView;
private Button mButton;
private Thread mThread;
private Handler mHandler = new Handler() {
public void handleMessage (Message msg) {//此方法在ui執行緒執行
switch(msg.what) {
case MSG_SUCCESS:
mImageView.setImageBitmap((Bitmap) msg.obj);//imageview顯示從網路獲取到的logo
Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_success), Toast.LENGTH_LONG).show();
break;
case MSG_FAILURE:
Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_failure), Toast.LENGTH_LONG).show();
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView= (ImageView) findViewById(R.id.imageView);//顯示圖片的ImageView
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mThread == null) {
mThread = new Thread(runnable);
mThread.start();//執行緒啟動
}
else {
Toast.makeText(getApplication(), getApplication().getString(R.string.thread_started), Toast.LENGTH_LONG).show();
}
}
});
}
Runnable runnable = new Runnable() {
@Override
public void run() {//run()在新的執行緒中執行
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet("http://csdnimg.cn/www/images/csdnindex_logo.gif");//獲取csdn的logo
final Bitmap bm;
try {
HttpResponse hr = hc.execute(hg);
bm = BitmapFactory.decodeStream(hr.getEntity().getContent());
} catch (Exception e) {
mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//獲取圖片失敗
return;
}
mHandler.obtainMessage(MSG_SUCCESS,bm).sendToTarget();//獲取圖片成功,向ui執行緒傳送MSG_SUCCESS標識和bitmap物件
// mImageView.setImageBitmap(bm); //出錯!不能在非ui執行緒操作ui元素
// mImageView.post(new Runnable() {//另外一種更簡潔的傳送訊息給ui執行緒的方法。
//
// @Override
// public void run() {//run()方法會在ui執行緒執行
// mImageView.setImageBitmap(bm);
// }
// });
}
};
}