Android数据缓存处理

     平时我们开发一个Android客户端的时候,谈到缓存处理更多的是关于图片的缓存,其实我们在开发类似于新闻客户端的时候,还需要考虑数据的缓存处理。通过数据的缓存处理,我们可以减少服务端的压力,减少用户的流量消耗。

    实现的方式主要是将客户端调用接口获取的列表数据缓存到相应目录下,以文件的形式保存下来,当下次进入界面,首先去缓存目录下找缓存文件,如果没有缓存文件,则直接调用网络接口去服务端获取;如果有缓存文件,还需要判断缓存文件的有效期,如果过了有效期,还是需要调用网络接口去获取最新的数据,拿到最新数据显示在界面并替换当前的缓存文件;如果没有过有效期,则直接拿出缓存文件的数据显示。

下面是缓存数据处理的几个函数:

//保存数据至缓存文件
	public boolean saveObject(Serializable ser, String file) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = sContext.openFileOutput(file, Context.MODE_PRIVATE);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(ser);
			oos.flush();
			return true;
		} catch (Exception e) {
			// e.printStackTrace();
			return false;
		} finally {
			try {
				oos.close();
			} catch (Exception e) {
			}
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}

	//判断指定缓存文件是否存在
	public boolean isExistDataCache(String cachefile) {
		boolean exist = false;
		File data = sContext.getFileStreamPath(cachefile);
		if (data.exists())
			exist = true;
		return exist;
	}

	private boolean isReadDataCache(String cachefile) {
		return readObject(cachefile) != null;
	}

	//判断缓存文件是否过了有效期
	public boolean isCacheDataFailure(String cachefile, int time) {
		boolean failure = false;

		if (!isReadDataCache(cachefile)) {
			failure = true;
		} else {
			File data = sContext.getFileStreamPath(cachefile);
			if (data.exists()
					&& ((System.currentTimeMillis() - data.lastModified()) > time || (System
							.currentTimeMillis() - data.lastModified()) < 0))
				failure = true;
			else if (!data.exists())
				failure = true;
		}
		return failure;
	}

	//读取指定缓存文件
	public Serializable readObject(String file) {
		if (!isExistDataCache(file))
			return null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = sContext.openFileInput(file);
			ois = new ObjectInputStream(fis);
			return (Serializable) ois.readObject();
		} catch (FileNotFoundException e) {
			return null;
		} catch (Exception e) {
			// e.printStackTrace();

			if (e instanceof InvalidClassException) {
				File data = sContext.getFileStreamPath(file);
				data.delete();
			}
			return null;
		} finally {
			try {
				ois.close();
			} catch (Exception e) {
			}
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
	}

	//清除指定缓存文件
	public boolean clearFileCache(String filecache) {
		boolean ret = false;
		if (isExistDataCache(filecache)) {
			File file = sContext.getFileStreamPath(filecache);
			file.delete();
			ret = true;
		}

		return ret;
	}

 通过上面的代码可以发现,数据是缓存在你应用目录的files文件下,也就是data/data/packageName/files/

使用方式:

1、读取缓存,并判断根据缓存来判断是否需要调用网络接口

//读取缓存文件
		Serializable object = AppState.getInstance().readObject(SystemConfig.KEY_HISTORY);
		if (object == null) {//不存在缓存文件
			if (AppState.getInstance().isNetworkConnected()) {
				//网络状态好的情况下直接调用接口获取数据
				startHistory();
			} else {
				showFailLayout();
			}
		} else {
			if (AppState.getInstance().isCacheDataFailure(SystemConfig.KEY_HISTORY,
					SystemConfig.CACHE_TIME)) {//缓存文件过了有效期(20分钟)
				if (AppState.getInstance().isNetworkConnected()) {
					startHistory();
				} else {
					showFailLayout();
				}
			} else {
				//获取缓存数据并显示
				mList = (ArrayList<TodayHistory>) object;
				mHandler.sendEmptyMessage(1);
			}
		}

 2、调用网络接口获取数据之后,显示并保存到缓存文件中

if (mList.size() > 0)
						AppState.getInstance().saveObject(mList, SystemConfig.KEY_HISTORY);
					mHandler.sendEmptyMessage(1);

 注意:保存到缓存文件的数据类型必须实现Serializable接口,因为读取和保存数据都是通过IO操作的。

欢迎去下载我的软件体验:http://android.myapp.com/myapp/detail.htm?apkName=com.yln.history

猜你喜欢

转载自yaolinnan.iteye.com/blog/2298009