一、运行效果图
二、核心代码
1.MainActivity的代码:
public class MainActivity extends Activity
{
private EditText et_path;
private ImageView iv;
//创建Handler对象
private Handler handler = new Handler(){
//处理消息
public void handleMessage(android.os.Message msg){
Bitmap bitmap = (Bitmap)msg.obj;
iv.setImageBitmap(bitmap);
};
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 找到我们关心的控件
et_path = (EditText) findViewById(R.id.et_path);
iv = (ImageView) findViewById(R.id.iv);
}
// 点击按钮进行查看指定路径的源码
public void click(View v){
new Thread(){
public void run(){
try
{
//缓存图片,谷歌给我们提供了一个缓存目录
File file = new File(getCacheDir(),"test.png");
/*if(file.exists()&& file.length()>0){
//使用缓存的图片
System.out.println("使用缓存图片");
Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//把cacheBitmap 显示到iv上
Message msg = Message.obtain();
msg.obj = cacheBitmap;
handler.sendMessage(msg);
}
else{*/
//第一次访问互联网获取数据
//System.out.println("第一次访问连接网络");
// 获取访问图片的路径
String path = et_path.getText().toString().trim();
// 创建url对象
URL url = new URL(path);
// 获取httpurlconnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求的方式
conn.setRequestMethod("GET");
// 设置超时时间
conn.setConnectTimeout(5000);
//获取服务器返回的状态码
int code = conn.getResponseCode();
if(code==200){
//获取图片的数据,不管是什么数据(txt文本 图片数据)都是以流的形式返回
InputStream in = conn.getInputStream();
/*
FileOutputStream fos = new FileOutputStream(file);
int len = -1;
byte[] buffer = new byte[1024];//1kb
while((len-in.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
fos.close();
in.close();*/
//通过位图工厂获取bitmap(bitmap)
Bitmap bitmap = BitmapFactory.decodeStream(in);
Message msg = Message.obtain();
msg.obj = bitmap;
handler.sendMessage(msg);
}
/*}*/
} catch (Exception e)
{
e.printStackTrace();
}
};
}.start();
}
}
2.activity_main的代码:
<EditText
android:id="@+id/et_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="http://img5q.duitang.com/uploads/item/201503/07/20150307203721_nnS2E.png">
</EditText>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="查看"/>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
三、遇到的问题
在进行图片缓存的时候,LogCat中显示主线程中加载的事件太多,程序没有错,但是不能点击图片查看。