您好,登錄后才能下訂單哦!
多線程從網絡下載圖片
利用了handler機制
package com.example.testhandler;
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 org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class TestHandler extends Activity {
private Button btnDown;
private ImageView img;
private static String p_w_picpath_path = "http://wenwen.soso.com/p/20100322/20100322095024-1008716746.jpg";
private ProgressDialog dialog;
private static int IS_FINISH = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDown = (Button) findViewById(R.id.btnDown);
img = (ImageView) findViewById(R.id.ivSinaImage);
dialog = new ProgressDialog(this);
dialog.setTitle("提示信息");
dialog.setMessage("正在下載中,請稍后...");
dialog.setCancelable(false);
btnDown.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(mRunnable).start();
dialog.show();
}
});
}
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(p_w_picpath_path);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
byte[] data = EntityUtils.toByteArray(httpResponse
.getEntity());
// 獲取一個Message對象,設置what為1
Message msg = Message.obtain();
msg.obj = data;
msg.what = IS_FINISH;
// 發送這個消息到消息隊列中
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
private Handler handler = new Handler() {
// 在Handler中獲取消息,重寫handleMessage()方法
@Override
public void handleMessage(Message msg) {
// 判斷消息碼是否為1
if(msg.what==IS_FINISH){
byte[] data=(byte[])msg.obj;
Bitmap bmp=BitmapFactory.decodeByteArray(data, 0, data.length);
img.setImageBitmap(bmp);
dialog.dismiss();
}
}
};
}
網絡權限
<uses-permission android:name="android.permission.INTERNET" />
activity_main.xml文件中只有兩個空間
一個Button按鈕 一個ImageView
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。