oschina-app源码解析-系统参数保存

来源:互联网 发布:微信公众号 java sdk 编辑:程序博客网 时间:2024/05/10 12:37

        最近研究了下oschina-app 的源码,有几个功能实现的挺不错,比如主页面的页面切换效果、开源UIGrendroid的使用、数据的缓存、以及html5的加载、页面动画使用等,在这里跟大家分享一下。

        主页面是否能切左右滑动是可以设置的,这种参数我经常是保存在sharepreference保存的,这里是用系统文件对Properties保存的。

 通过 Properties对参数数据的保存、获取、删除代码:

public String get(String key) {Properties props = get();return (props != null) ? props.getProperty(key) : null;}public Properties get() {FileInputStream fis = null;Properties props = new Properties();try {// 读取files目录下的config// fis = activity.openFileInput(APP_CONFIG);// 读取app_config目录下的configFile dirConf = mContext.getDir(APP_CONFIG, Context.MODE_PRIVATE);fis = new FileInputStream(dirConf.getPath() + File.separator+ APP_CONFIG);props.load(fis);} catch (Exception e) {} finally {try {fis.close();} catch (Exception e) {}}return props;}private void setProps(Properties p) {FileOutputStream fos = null;try {// 把config建在files目录下// fos = activity.openFileOutput(APP_CONFIG, Context.MODE_PRIVATE);// 把config建在(自定义)app_config的目录下File dirConf = mContext.getDir(APP_CONFIG, Context.MODE_PRIVATE);File conf = new File(dirConf, APP_CONFIG);fos = new FileOutputStream(conf);p.store(fos, null);fos.flush();} catch (Exception e) {e.printStackTrace();} finally {try {fos.close();} catch (Exception e) {}}}public void set(Properties ps) {Properties props = get();props.putAll(ps);setProps(props);}public void set(String key, String value) {Properties props = get();props.setProperty(key, value);setProps(props);}public void remove(String... key) {Properties props = get();for (String k : key)props.remove(k);setProps(props);}

以上为通过Properties对app参数的保存和读取,下面提供另一种方法SharedPreferences对参数对象的统一存储和读取,直接上代码

/** * 保存用户信息 *  * @throws IOException */public void saveUser() {ByteArrayOutputStream baos = new ByteArrayOutputStream();ObjectOutputStream oos;try {oos = new ObjectOutputStream(baos);oos.writeObject(mUser);String object64 = new String(Base64.encodeBase64(baos.toByteArray()));mPrefere.edit().putString("user", object64).commit();} catch (IOException e) {logUtil.i(e.toString());e.printStackTrace();}}/** * 获取用户信息对象 *  * @return * @throws StreamCorruptedException * @throws IOException * @throws ClassNotFoundException */public StudentInfo getUser() {StudentInfo user = null;try {String object64 = mPrefere.getString("user", "");byte[] buff = Base64.decodeBase64(object64.getBytes());ByteArrayInputStream bais = new ByteArrayInputStream(buff);ObjectInputStream ois;ois = new ObjectInputStream(bais);user = (StudentInfo) ois.readObject();} catch (Exception e) {logUtil.i(e.toString());// TODO Auto-generated catch blocke.printStackTrace();}return user;}

读写过程,先开辟一块内存空间,对数据进行编解码,在对对象就行读写。我建议尽量使用文件来储存参数和临时参数,尽量避免由于系统回收,把静态参数给销毁,导致不必要的异常。

oschina-app完整源码下载:http://download.csdn.net/detail/xiangxue336/7023661

0 0
原创粉丝点击