您好,登錄后才能下訂單哦!
多線程從網(wǎng)絡(luò)下載圖片
利用了handler機(jī)制
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("正在下載中,請(qǐng)稍后...");
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());
// 獲取一個(gè)Message對(duì)象,設(shè)置what為1
Message msg = Message.obtain();
msg.obj = data;
msg.what = IS_FINISH;
// 發(fā)送這個(gè)消息到消息隊(duì)列中
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();
}
}
};
}
網(wǎng)絡(luò)權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
activity_main.xml文件中只有兩個(gè)空間
一個(gè)Button按鈕 一個(gè)ImageView
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。