標籤:des android http io ar os java for sp
在寫這篇博文的時候,我參與了一個項目的開發,裡面涉及了非常多網路調用相關的問題,我記得我在剛剛開始做android項目的時候,以前就遇到這個問題,當時在網上搜尋了一下,發現了一篇博文,如今與大家分享一下,http://www.open-open.com/lib/view/open1376128628881.html
事實上這篇文章的思想是有問題的,由於網路是需要不斷的輪詢訪問的,所以必需要放線上程中,而不應該直接放在onCreate方法中,我對這段程式進行了一定的改動,將它們放線上程中更新就能夠了。
這個事MainActivity.java的代碼:
package com.test.picture;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.widget.ImageView;public class MainActivity extends Activity {private ImageView imageView;private String picturePath = "http://content.52pk.com/files/100623/2230_102437_1_lit.jpg";@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfinal Bitmap bitmap = returnBitMap(picturePath);imageView.post(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubimageView.setImageBitmap(bitmap);}});}}).start();}private Bitmap returnBitMap(String url) {URL myFileUrl = null;Bitmap bitmap = null;try {myFileUrl = new URL(url);} catch (MalformedURLException e) {e.printStackTrace();}try {HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();conn.setDoInput(true);conn.connect();InputStream is = conn.getInputStream();bitmap = BitmapFactory.decodeStream(is);is.close();} catch (IOException e) {e.printStackTrace();}return bitmap;}private void initView() {imageView = (ImageView) findViewById(R.id.picture);}}
這是布局檔案的代碼:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/display_image" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" > <ImageView android:id="@+id/picture" android:layout_width="wrap_content" android:layout_height="wrap_content" /></LinearLayout>
當然我們也要在AndroidManifest.xml中加入?對應的網路許可權。
我們在MainActivity.java中的onCreate方法中建立了一個新的線程,可是我們也明確不能夠在非UI線程中操作使用者介面,那麼我們不能夠直接在新的線程中操作UI,所以我們還要將改變post到UI線程中去。
上面的方法執行時沒有問題的,謝謝大家。
Android網狀圖片顯示在ImageView 上面