1. 在此執行個體中,重點展示使用Android平台提供的互連網網路訪問方式以及圖片顯示問題.
按照如下的配置以及在開發循序漸進執行個體1中描述的方法建立整個項目Base:
project Name: ExampleFive
Platform: Android2.0;
Application name: ExampleFive
package name: com.example
Activity: MainActivity
Resource file: main.xml
此Resource檔案沒有任何資源配置;
在AndroidManifest.xml中選擇Permissions->Add...->選擇Uses Permission->點擊OK,在右邊的Attributes for Uses Permission下面的下拉式清單中選擇android.permission.INTERNET->選擇CTRL+S儲存結果。
2. 在MainActivity中加入如下的代碼顯示函數:
private void showImage() {
ImageView iv = new ImageView(this);
iv.setBackgroundColor(0xFFFFFFFF);
iv.setScaleType(ScaleType.FIT_CENTER);
iv.setLayoutParams(new Gallery.LayoutParams(40, 40));
downloadAndShowInternetFile("http://www.twicular.com/images/top_07.png", iv);
this.setContentView(iv);
}
void downloadAndShowInternetFile(String url, ImageView iv) {
URL internetUrl = null;
try {
internetUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) internetUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bmImg = BitmapFactory.decodeStream(is);
iv.setImageBitmap(bmImg);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
3. 在MainActivity中的onCreate()重載函數添加如下的調用代碼:
showImage();
4. 運行即可看到首頁顯示的是一張圖片(Twicular公司的LOGO);
本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/jackxinxu2100/archive/2010/01/27/5261105.aspx