1、MainThread的OnCreate函数添加
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
.penaltyLog().penaltyDeath().build());
2、 添加子线程,用子线程进行网络访问
new Thread(){
@Override
public void run()
{
//把网络访问的代码放在这里
}
}.start();
3、 继承AsyncTask类
class DownImage extends AsyncTask {
private ImageView imageView;
public DownImage(ImageView imageView) {
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
Bitmap bitmap = null;
try {
//加载一个网络图片
InputStream is = new URL(url).openStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}