当前位置: 首页 > 工具软件 > ASimpleCache > 使用案例 >

android ASimpleCache

蓝夕
2023-12-01

轻量级Anndroid缓存框架ASimpleCache之缓存网络数据

ASimpleCache是一种基于Android的轻量级缓存框架,
它的大小仅仅只有一个Java文件(简化而来),一目了然。

1、ASimpleCache可以缓存什么类型呢
(1)字符串
(2)JSON对象
(3)序列化的Java对象
(4)Bitmap
(5)byte数据

2、ASimpleCache有什么特点呢
(1)小:小到只有Java文件。
(2)可以配置:设置缓存路径,大小及缓存的数量等。
(3)可以设置缓存时间,超时自动失效并删除。
(4)可以支持多进程。

3、ASimpleCache的使用场景在android中
(1)替换SharePreference当做配置文件。
(2)可以缓存网络请求,作为app数据。
(3)可以作为预加载数据的缓存库。

1.1使用ASimpleCache之前先把Java文件放到项目中,文件名称IsNet,

代码部分:

public class IsNet {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected())
{
// 当前网络是连接的
if (info.getState() == NetworkInfo.State.CONNECTED)
{
// 当前所连接的网络可用
return true;
}
}
}
return false;
}
}
把这个放进去就好了,接下来就到缓存的时候了。

1.1缓存字符串
首先,创建ASimpleCache对象:
private ACache mACache;

mACache = ACache.get(this);

其次储存数据:
mACache.put(Constants.KEY_STRNG,result);
然后获取缓存数据:
String result=mACache.getAsString(Constants.KEY_STRING);
最后清除缓存:
mACache.remove(Constants.KEY_STRING);

1.2JsonObject
首先,创建ASimpleCache对象:
private ACache mACache;

mACache = ACache.get(this);
其次存储数据:
mACache.put(Constants.KEY_JAVA_BEAN,mWeather);
还有,获取缓存数据:
Weather result = (Weather) mACache.getAsObject(Constants.KEY_JAVA_BEAN);
最后,清除缓存:
mACache.remove(Constants.KEY_JAVA_BEAN);
1.7缓存byte数据
首先,创建ASimpleCache对象:
private ACache mACache;

mACache = ACache.get(this);
其次,存储数据:
private void saveByte() {
OutputStream ostream = null;
try {
ostream = mACache.put(Constants.KEY_BYTE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (ostream == null) {
ToastUtil.simpleToast(this, “Open stream error!”);
return;
}
try {
URL u = new URL(Constants.downloadUrl);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.connect();
InputStream stream = conn.getInputStream();
byte[] buff = new byte[1024];
int counter;
while ((counter = stream.read(buff)) > 0) {
ostream.write(buff, 0, counter);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// cache update
ostream.close();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
showTv.setText(“done…”);
}
});
}
}
还有,获取缓存数据:
private void getsByte() {
InputStream stream = null;
try {
stream = mACache.get(Constants.KEY_BYTE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (stream == null) {
ToastUtil.simpleToast(this, “Bitmap cache is null …”);
showTv.setText(“file not found”);
return;
}
try {
showTv.setText("file size: " + stream.available());
} catch (IOException e) {
showTv.setText("error " + e.getMessage());
}
}
最后,清除缓存:
mACache.remove(Constants.KEY_BYTE);

有人会问网络缓存呢?别着急,
我写了一个小列子。

代码如下:
先写网络权限:

需要添加一个个wife权限
                   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
                   如果不添加的话就会报SecurityException: ConnectivityService: Neither user 10044 nor current process has android.permission.ACCESS_NETWORK_STATE.这个错,还有一个是网络权限,
                 
               
   <uses-permission android:name="android.permission.INTERNET" />   

 /**
     * 检测网络是否可用
     *
     * @return
     */
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                initQingqiu();
            } else {
                ACache mCache = ACache.get(getContext());
                // mCache.put("test_key2", "test value", 3000);//保存10秒,如果超过10秒去获取这个key,将为null
                // mCache.put("test_key3", "test value", 2 * ACache.TIME_DAY);//保存两天,如果超过两天去获取这个key,将为null
                //获取数据
                value = mCache.getAsString("zwj");
                Gson gson = new Gson();
                Bean bean = gson.fromJson(value, Bean.class);
                List<Bean.ResultBean.DataBean> data = bean.getResult().getData();
                Log.e("asdfasdfsadf", data.toString());
                list2.addAll(data);
                adapter = new RecyAdapter(list2, getActivity());
                recycelrview.setLayoutManager(new LinearLayoutManager(getContext()));
                recycelrview.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                return false;
            }
        } else {
            return false;
        }
        return false;
    }
 //请求数据
    private void initQingqiu() {
        OkhttpUtils.getInstance().setGet("http://v.juhe.cn/toutiao/index?type=top&key=097060266650f67b2cebd2a06aded587", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                string = response.body().string();
                Log.e("TAG", string.toString());
                Gson gson = new Gson();
                ACache mCache = ACache.get(getContext());
                mCache.put("zwj", string, 3000);
                Bean bean = gson.fromJson(string, Bean.class);
                List<Bean.ResultBean.DataBean> data = bean.getResult().getData();
                list2.addAll(data);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                        if (sw.isRefreshing()) {
                            sw.setRefreshing(false);
                        }
                    }
                });
            }
        });

    }

最后xml部分:


        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycelrview"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </android.support.v7.widget.
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycelrview"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </android.support.v7.widget.RecyclerView>>

仅仅只是一个RecyclerView,哈哈,简单吧。

谢谢大家,如果有需要的话可以交流交流

 类似资料:

相关阅读

相关文章

相关问答