Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android:緩存服務器數據為本地存儲

android:緩存服務器數據為本地存儲

編輯:關於Android編程

 

兩個開源代碼 實現想法 簡單實現的一些簡化做法

兩個開源代碼

也足夠用了,沒必要自己去寫,文件很小
- reservoir 緩存對象為字符串;
- disklrucache 存取sd卡工具;

實現想法

也就是將接口的字符串緩存到本地而已;不一定是網絡緩存,可以指定任何想要的字符串保存,如果願意可以用數據庫等等,看需要咯,減輕服務器加載壓力

在保證接口正常調用的情況下嵌入緩存管理方式,不對之前的代碼造成任何影響,且方便替換; 不同的接口可以自定義緩存的過期時間,這個時間可以是服務器接口的時間,也可以是本地定死的時間; 加載邏輯為每次先將該接口字段所有數據toString()後做一個MD5作為鍵,同時將寫入時間和緩存時間保存下來;取出的時候根據當前時間和寫入時間以及緩存時間去判斷緩存是否可用;

由於很簡單這個可用花點時間做的更好點,比如不同接口不同時間,完全使用緩存還是緩存過期後仍使用緩存,等待網絡加載完成後重新寫入等等看需要;

不同項目不同網絡層,網絡加載的使用之前寫過一個,在這裡:
http://blog.csdn.net/intbird/article/details/38338623

簡單實現的一些簡化做法

對於緩存的額外信息需要的不是很大,所以判斷換存時間的方式不是Map

    private final static int initialCapacity = 1*1024*1024;
    private final static String key_time_mills = timeMills;
    private static LinkedHashMap cacheTimeMills;

    private final static String key_time_valid = timeValid;
    private static LinkedHashMap cacheTimeValid;

改寫接口代碼:


    protected boolean postCheck(final Context context, final boolean isShow, final String content,PostUrlInfo postUrlInfo,final RequestParams params, final IParser iParse, final INetCallBack callBack){
        //如果不使用緩存,網絡加載
        if(postUrlInfo.isEnabledCache()==false) return false;
        //嘗試獲取緩存數據,如果緩存未過期,重點在get方法裡;
        String response = Reservoir.get(postUrlInfo.reqIndentKey, String.class);
        if(TextUtils.isEmpty(response)) return false;
        //直接使用網絡層正常解析方法,但標記為緩存加載
        //不在放入緩存,做一些處理;
        DialogFragment dialogFragment = new ProgressDialogFragment(content);
        ParseResult parseResult = new ParseResult();
        parseResult.isNetParse = false;

        parseTask task = new parseTask(dialogFragment, iParse, callBack, 0,getDefaultHeaders(params), response,postUrlInfo,parseResult);
        task.execute();
        //做原網絡解析,返回不在進行網絡加載;
        return true;
    }

    //重新整理原接口,將Url信息封裝,方便計算key;
    protected void post(final Context context, final boolean isShow, final String content,String relativePath,final RequestParams params, final IParser iParse, final INetCallBack callBack) {
        PostUrlInfo urlInfo = new PostUrlInfo(BaseURL,relativePath);
        post(context, isShow, content,urlInfo, params, iParse, callBack);
    }

    //添加一個緩存時間擴展原接口,檢查cacheTime CacheEnable()方法;
    protected void post(long cacheTime,final Context context, final boolean isShow, final String content,String relativePath,final RequestParams params, final IParser iParse, final INetCallBack callBack) {
    //也可以使用host:port:ralaUrl的方式,已封裝看情況;
        PostUrlInfo urlInfo = new PostUrlInfo(BaseURL,relativePath);
        urlInfo.setDefaultCacheTime(cacheTime);
        post(context, isShow, content,urlInfo, params, iParse, callBack);
    }

    //真實加載方式
    protected void post(final Context context, final boolean isShow, final String content,final PostUrlInfo postUrlInfo,final RequestParams params, final IParser iParse, final INetCallBack callBack) {
        if(params == null) {
            return;
        }
        Logger.i(postUrlInfo.getPostUrl());
        Logger.i(params.toString());

        //計算該次接口的key值,檢查緩存,getReqIdentifiter可去除要計算
        //的postKey,比如單次隨機數等;
        postUrlInfo.reqIndentKey = 
        getReqIdentifiter(postUrlInfo,params);
        if(postCheck(context, isShow, content,postUrlInfo,
             params, iParse, callBack)){
            return ;
        }
        //使用網絡加載後,將網絡層數據放入緩存
        //Reservoir.put(postUrlInfo.reqIndentKey,
        //response,postUrlInfo.getDefaultCacheTime());

        //正常網絡加載    
        client.post(context, postUrlInfo.getPostUrl(), (org.apache.http.Header[]) getDefaultHeaders(params), params,null, new AsyncHttpResponseHandler() {};

一個JAVA AES加密的代碼文件 EnDecrypt.java

package com.anupcowkur.reservoir;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class EnDecrypt {

    public static String encrypts(String sourContent,String password){
        try{
            byte[] encryptResult = encrypt(sourContent, password);  
            return parseByte2HexStr(encryptResult); 
        }catch(Exception ex){
            return sourContent;
        }
    }
    public  static String decrypts(String cryContent,String password){
        try{
            byte[] decryptFrom = parseHexStr2Byte(cryContent);  
            byte[] decryptResult = decrypt(decryptFrom,password);  
            return  new String(decryptResult);
        }catch(Exception ex){
            return cryContent;
        }
    }

    private static byte[] encrypt(String content, String password) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {  
        KeyGenerator kgen = KeyGenerator.getInstance(AES);  
        kgen.init(128, new SecureRandom(password.getBytes()));  
        SecretKey secretKey = kgen.generateKey();  
        byte[] enCodeFormat = secretKey.getEncoded();  
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES);  
        Cipher cipher = Cipher.getInstance(AES);// 創建密碼器   
        byte[] byteContent = content.getBytes(utf-8);  
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化   
        byte[] result = cipher.doFinal(byteContent);  
        return result; // 加密   
    }

    private static byte[] decrypt(byte[] content, String password) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {  
         KeyGenerator kgen = KeyGenerator.getInstance(AES);  
         kgen.init(128, new SecureRandom(password.getBytes()));  
         SecretKey secretKey = kgen.generateKey();  
         byte[] enCodeFormat = secretKey.getEncoded();  
         SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES);              
         Cipher cipher = Cipher.getInstance(AES);// 創建密碼器   
         cipher.init(Cipher.DECRYPT_MODE, key);// 初始化   
         byte[] result = cipher.doFinal(content);  
         return result; // 加密   
    }

    private static String parseByte2HexStr(byte buf[]) {  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < buf.length; i++) {  
                String hex = Integer.toHexString(buf[i] & 0xFF);  
                if (hex.length() == 1) {  
                        hex = '0' + hex;  
                }  
                sb.append(hex.toUpperCase());  
        }
        return sb.toString();
    }

    private static byte[] parseHexStr2Byte(String hexStr) {  
        if (hexStr.length() < 1)  
                return null;  
        byte[] result = new byte[hexStr.length()/2];  
        for (int i = 0;i< hexStr.length()/2; i++) {  
                int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);  
                int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);  
                result[i] = (byte) (high * 16 + low);  
        }  
        return result;  
    } 

    public static String md5(String s) {
        try {
            MessageDigest m = MessageDigest.getInstance(MD5);
            m.update(s.getBytes(UTF-8));
            byte[] digest = m.digest();
            BigInteger bigInt = new BigInteger(1, digest);
            return bigInt.toString(16);
        } catch (NoSuchAlgorithmException e) {
            throw new AssertionError();
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError();
        }
    }
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved