1、新建一个XML,写一个Button,Imgview
<ImageView
android:id="@+id/imgviews"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/butns"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AsyncTask网络取图"/>
2、新建一个Activty继承Activty,
这里对于控件实例化就不写出来了,直接进入主题
//点击按钮mButton获取网络图片
mButton2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
getBitmapByAsyncTask("http://www.jimeise.net/wp-content/uploads/2014/05/IMGP6150.jpg");
}
});
}
private void getBitmapByThread(final String httpUrls){
new Thread() {
public void run() {
URL url;
try {
url = new URL(httpUrls);
HttpURLConnection connect = (HttpURLConnection) url
.openConnection();
InputStream is = connect.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
Message msg = Message.obtain();
msg.obj = bitmap;
mHandler.sendMessage(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
//用AsyncTask进行网络取图片
private void getBitmapByAsyncTask(String httpUrl) {
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... params) {
String httpurl = params[0];
return DownLoadBitmap(httpurl);
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
ImageView2.setImageBitmap(result);
} else {
Toast.makeText(MainActivity.this, "网络取图片出错!",
Toast.LENGTH_SHORT).show();
}
};
}.execute(httpUrl);
}
private Bitmap DownLoadBitmap(String httpUrl) {
URL url;
Bitmap bitmap = null;
HttpURLConnection connect = null;
InputStream is = null;
try {
url = new URL(httpUrl);
connect = (HttpURLConnection) url.openConnection();
is = connect.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (connect != null) {
connect.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
里面全部是通过封装了的,直接调用。
强调一点就是网络取图片一定要在manifest里注册网络权限:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>