Android開發循序漸進執行個體5–網路訪問例子

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.