在写这篇博文的时候,我参与了一个项目的开发,里面涉及了很多网络调用相关的问题,我记得我在刚刚开始做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";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
final Bitmap bitmap = returnBitMap(picturePath);
imageView.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
imageView.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>
我们在MainActivity.java中的onCreate方法中创建了一个新的线程,但是我们也明白不可以在非UI线程中操作用户界面,那么我们不可以直接在新的线程中操作UI,所以我们还要将改变post到UI线程中去。
上面的方法运行时没有问题的,谢谢大家。
原文:http://blog.csdn.net/litianpenghaha/article/details/40045455