Android 离线app实现
2019-05-22 本文已影响185人
1a473fcb13b0
最近公司要弄一个离线的app
实现思路:先加载本地数据如果没有则使用开始使用网络加载,如果加载成功后,之后就可以一直使用本地数据。
MainActivity.java
/**
* 获取本地数据,如果本地没有数据则通过网络获取
*/
private void loadData() {
String skinCareIndexJson = CacheUtils.readJson("index.json");
if (!StrUtil.isEmpty(skinCareIndexJson) && !CacheUtils.isCacheDataFailure("index.json")) {
try {
parseJson(new JSONObject(skinCareIndexJson));
} catch (JSONException e) {
e.printStackTrace();
loadHttpData();
}
} else {
loadHttpData();
}
}
/**
* 通过网络获取数据
*/
private void loadHttpData() {
if (hasInternet()) {
HttpRestClient.post(Urls.INDEX + "userId=" + PreferencesUtil.getUserPreferences(UserPref.UserId), null, new JsonHttpResponseCallback() {
@Override
public void callback(int statusCode, JSONObject response) {
if (response == null) {
AppManager.showToastMessage("视频获取数据失败~!");
mTopImageLoopAdapter.notifyDataSetChanged();
return;
}
int result = response.optInt("result");
if (result == 0) {
AppManager.showToastMessage(response.optString("info"));
mTopImageLoopAdapter.notifyDataSetChanged();
return;
}
JSONObject datas = response.optJSONObject("datas");
parseJson(datas);
CacheUtils.writeJson(datas.toString(), "index.json");
}
});
} else {
AppManager.showToastMessage(getResources().getString(R.string.internet_error));
mTopImageLoopAdapter.notifyDataSetChanged();
}
}
private void parseJson(JSONObject datas){
hotFlagVideoList.clear();
hotFlagVideoList.addAll(JsonUtil.getListFromJSON(datas.optJSONArray("hotFlagVideoList"), Video[].class));
mTopImageLoopAdapter.notifyDataSetChanged();
}
CacheUtils.java
package com.mlx.lhsc.util;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class CacheUtils {
public static int CACHE_TIME_DAY_NUM = 7;
public static int CACHE_TIME_ONE_DAY = 1000 * 60 * 60 * 24 * CACHE_TIME_DAY_NUM;
private static BufferedWriter bw = null;
private static BufferedReader br = null;
/**
* 判断文件缓存是否过期
*
* @param fileName
* @return true 为过期
*/
public static boolean isCacheDataFailure(String fileName) {
String cacheRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LDM/json/";
File file = new File(cacheRoot);
if (!file.exists()) {
file.mkdirs();
}
File data = new File(cacheRoot, fileName);
boolean failure = false;
if ((System.currentTimeMillis() - data.lastModified()) > CACHE_TIME_ONE_DAY)
failure = true;
else if (!data.exists())
failure = true;
return failure;
}
/**
* 存储Json文件
*
* @param json json字符串
* @param fileName 存储的文件名
*/
public static void writeJson(String json,String fileName) {
String cacheRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LDM/json/";
File file = new File(cacheRoot);
if (!file.exists()) {
file.mkdirs();
}
String formatJson = JsonFormatUtils.format(json);
try {
File cacheFile = new File(cacheRoot, fileName);
bw = new BufferedWriter(new FileWriter(cacheFile));
bw.newLine();
bw.write(formatJson);
Log.e("storeJson", "保存数据到本地文件夹中:" + cacheFile);
bw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
bw = null;
}
}
/**
* 读取json数据
* @param fileName
* @return 返回值为list
*/
public static String readJson(String fileName) {
String cacheRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LDM/json/";
File file = new File(cacheRoot);
if (!file.exists()) {
file.mkdirs();
}
File cacheFile = new File(cacheRoot, fileName);
StringBuffer stringBuffer = new StringBuffer();
try {
br = new BufferedReader(new FileReader(cacheFile));
while (br.ready()) {
stringBuffer.append(br.readLine().trim());
}
br.close();
return stringBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
}finally {
br = null;
}
return null;
}
}