1.添權重限(通路網絡權限)
2.建立異步請求對象
3.執行post請求(指定url路徑,建立asynchttpresponsehandler方法)
a) 如果成功建立工廠對象
b) 工廠對象的decodebytearray把位元組轉換成bitmap對象
c) 設定圖檔
項目要求:通過edittext文本輸入框中的網址,點選檢視按鈕,進行網絡圖檔顯示
運作效果如下:
重點代碼:均有詳細解析,請認真檢視注釋
1、在androidmanifest.xml中添權重限
<uses-permission android:name="android.permission.internet"/>
2、布局檔案activity_main.xml
package com.example.photowatch;
import org.apache.http.header;
import android.app.activity;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.os.bundle;
import android.view.view;
import android.widget.edittext;
import android.widget.imageview;
import com.loopj.android.http.asynchttpclient;
import com.loopj.android.http.asynchttpresponsehandler;
public class mainactivity extends activity {
private edittext et_url;
private imageview img_info;
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
// 擷取控件對象
et_url = (edittext) findviewbyid(r.id.et_url);
img_info = (imageview) findviewbyid(r.id.img_info);
};
public void show(view v) {
int id = v.getid();
switch (id) {
case r.id.btn_show:
//請求位址
string url = et_url.gettext().tostring();
//建立網絡請求對象
asynchttpclient client= new asynchttpclient();
client.get(url, new asynchttpresponsehandler() {
@override
public void onsuccess(int statuscode, header[] headers, byte[] responsebody) {
if (statuscode == 200) {
//建立工廠對象
bitmapfactory bitmapfactory = new bitmapfactory();
//工廠對象的decodebytearray把位元組轉換成bitmap對象
bitmap bitmap = bitmapfactory.decodebytearray(responsebody, 0, responsebody.length);
//設定圖檔
img_info.setimagebitmap(bitmap);
}
}
public void onfailure(int statuscode, header[] headers,
byte[] responsebody, throwable error) {
error.printstacktrace();
});
break;
default:
}
}
}
3、mainactivity.java
重點代碼就是這些,自己動手檢視一下效果吧!~
開源架構資源:http://download.csdn.net/detail/zhaoyazhi2129/7400787
源碼:http://download.csdn.net/detail/zhaoyazhi2129/7400815
轉發請标明原文位址 http://blog.csdn.net/zhaoyazhi2129/article/details/27048527