Android-带缓存的网络图片查看(网络编程)

来源:互联网 发布:阿里云余额怎么使用 编辑:程序博客网 时间:2024/06/05 06:44

从网络中获取图片,第一次从网络中下载缓存到内存中,第二次的访问的时候直接从缓存中读取,此方法用来减少流量消耗;

资源直接放在tomcat的Tomcat7\webapps\ROOT\mytest\目录下,方便测试;

效果图:



使用到的权限:

<uses-permission android:name="android.permission.INTERNET"/>


布局文件:

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.android06.MainActivity" >    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:onClick="click"        android:text="下载图片" />    <ImageView        android:id="@+id/iv"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></RelativeLayout>

MainActivity.java

package com.example.android06;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import com.example.android06.R.id;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.util.Log;import android.view.View;import android.widget.ImageView;import android.widget.Toast;public class MainActivity extends Activity {public ImageView imageView;public Handler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageView = (ImageView) findViewById(R.id.iv);// 此方法在主线程中调用,可以用来刷新uihandler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);// 处理消息时,需要知道到底是成功的消息,还是失败的消息switch (msg.what) {case 1:// 把位图对象显示至imageviewimageView.setImageBitmap((Bitmap) msg.obj);break;case 0:Toast.makeText(MainActivity.this, "请求失败",Toast.LENGTH_SHORT).show();break;default:break;}}};}public void click(View view) {// 下载图片// 1.确定网址final String path = "http://192.168.47.25:8080/mytest/aa.jpg";final File file = new File(getCacheDir(), getFileName(path));// 判断,缓存中是否存在该文件if (file.exists()) {Toast.makeText(MainActivity.this, "从缓存中读取图片", Toast.LENGTH_SHORT).show();Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());imageView.setImageBitmap(bm);} else {Toast.makeText(MainActivity.this, "从网上下载图片", Toast.LENGTH_SHORT).show();Thread thread = new Thread() {@Overridepublic void run() {super.run();try {// 2.把网址封装成一个url对象URL url = new URL(path);// 3.获取客户端和服务器的连接对象,此时还没有建立连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 4.对连接对象进行初始化// 设置请求方法,注意大写connection.setRequestMethod("GET");// 设置连接超时connection.setConnectTimeout(5000);// 设置读取超时connection.setReadTimeout(5000);// 5.发送请求,与服务器建立连接connection.connect();// 如果响应码为200,说明请求成功if (connection.getResponseCode() == 200) {// 获取服务器响应头中的流,流里的数据就是客户端请求的数据InputStream is = connection.getInputStream();// 读取服务器返回的流里的数据,把数据写到本地文件,缓存起来FileOutputStream fos = new FileOutputStream(file);byte[] b = new byte[1024];int len = 0;while ((len = is.read(b)) != -1) {fos.write(b, 0, len);}fos.close();// 读取出流里的数据,并构造成位图对象// 流里已经没有数据了Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());Message msg = new Message();// 消息对象可以携带数据msg.obj = bm;msg.what = 1;// 把消息发送至主线程的消息队列handler.sendMessage(msg);} else {Message msg = handler.obtainMessage();msg.what = 0;handler.sendMessage(msg);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}};thread.start();}}public String getFileName(String path) {// 得到最后“/”的索引int index = path.lastIndexOf("/");// 得到字符串aa.jpgreturn path.substring(index + 1);}}

总结:URL地址一定要正确,上面的地址不是固定的,若要确定先在浏览器中验证;(localhost:8080不行)

 


        

0 0
原创粉丝点击