萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 安卓開發 >> android通過http協議獲得圖片

android通過http協議獲得圖片

 android通過圖片網址獲得圖片並顯示在imageView中。

下面就簡單的來說明操作過程:

首先必須在布局文件中聲明imageView控件:

<ImageView 
android:id="@+id/image" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" />

還必須在清單文件中加入訪問網絡的權限:

<uses-permission android:name="android.permission.INTERNET" />

其次:用一個service類來實現訪問http協議,並且獲得鏈接的返回值這個過程:htmlPath是圖片的網絡地址

public class PageService { 
/**@description:獲取圖片的數據 
* @author:Administrator 
* @return:byte[] 
* @param htmlpath 
* @return 
* @throws Exception 
*/ 

public static byte[] getImage(String htmlpath) throws Exception { 
byte[] imagearray = null; 
URL url = new URL(htmlpath); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
conn.setConnectTimeout(5000); 
// conn.setRequestMethod("GET"); 
conn.connect(); 
if (conn.getResponseCode() == 200) { 
byte[] buffer = new byte[1024]; 
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); 
int len = 0; 
InputStream inputStream = conn.getInputStream(); 
while ((len = inputStream.read(buffer)) != -1) { 
arrayOutputStream.write(buffer, 0, buffer.length); 

imagearray = arrayOutputStream.toByteArray(); 

return imagearray; 



最後在activity中啟用一個線程來調用這個業務方法,並在handler中對UI進行更新:(必須實現線程否則會出錯,這是和3.0版本之前不同的地方)

public class MainActivity extends Activity { 
private EditText strpath; 
private TextView htmlcontent; 
private ImageView imageview; 
Handler handler=new Handler(){ 

@Override 
public void handleMessage(Message msg) { 
byte[] data=(byte[])msg.obj; 
Bitmap image=BitmapFactory.decodeByteArray(data, 0, data.length); 
imageview.setImageBitmap(image);}


下面是線程中的內容:

private final class ImageThread extends Thread { 

@Override 
public void run() { 
String htmlpath=strpath.getText().toString(); 
htmlpath="http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif"; 
byte[] htmlarray=null; 
try { 
htmlarray=PageService.getImage(htmlpath); 
} catch (Exception e) { 
e.printStackTrace(); 

Message msg=new Message(); 
msg.obj=htmlarray; 
msg.what=1; 
handler.sendMessage(msg); 


}

最後用點擊一個button來觸發獲取圖片的事件:

private final class ButtonClickListener implements View.OnClickListener { 

@Override 
public void onClick(View v) { 
ImageThread thread=new ImageThread(); 
thread.start(); 

}

好了,介紹完畢。

最後如果獲取的內容為html頁面的內容的話,如果內容過長,就需要用滾動條來顯示:

可以在TextView外面加上ScollView加載滾動條:

<ScrollView 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" > 

<TextView 
android:id="@+id/htmlcontent" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" /> 
</ScrollView>  

copyright © 萬盛學電腦網 all rights reserved