从网络中请求图片进行缓存
先看一下最终效果图:
好,接下来开始实现整个程序:
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.httpimg.MainActivity" >
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
/>
</RelativeLayout>
MainActivity.java:
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView iv;
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
iv.setImageBitmap((Bitmap) msg.obj);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.img);
//http://pic.baike.soso.com/p/20090711/20090711101754-314944703.jpg
new Thread(new Runnable() {
@Override
public void run() {
getImg();
}
}){}.start();
}
protected void getImg() {
try {
URL url = new URL("http://pic.baike.soso.com/p/20090711/20090711101754-314944703.jpg");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//默认是get请求 如果想使用post必须指明
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
int code = connection.getResponseCode();
if(code == 200){
InputStream inputStream = connection.getInputStream();
//因为该地址是一个图片的地址,所以返回的数据流就是一个图片的数据流
//直接用该图片的数据流 转换成 一个Bitmap
Bitmap bit = BitmapFactory.decodeStream(inputStream);
//因为子线程不能更新UI 所以使用Handler完成
Message message = Message.obtain();
message.obj = bit;
handler.sendMessage(message);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
好了,这就是整个程序的实现过程,希望对大家有所帮助!