最近研究了下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目錄下的config
File 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 block
e.printStackTrace();
}
return user;
}
讀寫過程,先開闢一塊內存空間,對數據進行編解碼,在對對象就行讀寫。我建議儘量使用文件來儲存參數和臨時參數,儘量避免由於系統回收,把靜態參數給銷燬,導致不必要的異常。
oschina-app完整源碼下載:http://download.csdn.net/detail/xiangxue336/7023661