缓存工具类封装
16lz
2021-01-23
package com.yaoxin.newapp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.List;
import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class Utils {
public static final String STRING_NO_POINT = "";
public static Context applicationContext;
public static final int LEVEL_INTERN = 0;
public static final int LEVEL_NORMAL = 1;
public static final int LEVEL_PHARMACIST = 6;
public static final int LEVEL_LICENSED_PHARMACIST = 7;
/**
* 检测是否有可用网络
*
* @param context
* @return 网络连接状态
*/
public static boolean isNetworkAvailable(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// 获取网络信息
NetworkInfo info = cm.getActiveNetworkInfo();
// 返回检测的网络状态
return (info != null && info.isConnected() && info.isAvailable());
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static boolean isWifiConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWiFiNetworkInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWiFiNetworkInfo != null) {
return mWiFiNetworkInfo.isAvailable();
}
}
return false;
}
public static boolean isMobileConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mMobileNetworkInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mMobileNetworkInfo != null) {
return mMobileNetworkInfo.isAvailable();
}
}
return false;
}
/*
* 获取当前的网络状态 -1:没有网络 1:WIFI网络 2:wap网络 3:net网络
*
* */
public static int getConnectedType(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager
.getActiveNetworkInfo();
if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
return mNetworkInfo.getType();
}
}
return -1;
}
//获取缓存文件名
public static String getCacheFileName(String filename){
String cacheDir = applicationContext.getFilesDir().getAbsolutePath();
if (filename.startsWith("/")){
return cacheDir + filename;
} else{
return cacheDir + "/" + filename;
}
}
//将String内容保存到文件中
//返回值: true - 成功 false - 失败
public static Boolean saveContentToFile(String content, String filename){
try{
File f = new File(filename);
if (!f.exists()){
f.getParentFile().mkdirs();
f.createNewFile();
}
FileOutputStream ofile = new FileOutputStream(f);
ofile.write(content.getBytes());
ofile.close();
return true;
} catch (Exception e){
return false;
}
}
//将String内容保存到缓存文件中,自动为filename文件名添加缓存路径
//返回值: true - 成功 false - 失败
public static Boolean saveStringToCacheFile(String content, String filename){
return saveContentToFile(content, getCacheFileName(filename));
}
//读取文件内容
public static String getContentFromFile(String filename){
String res = "";
try{
FileInputStream fin = new FileInputStream(filename);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}
catch(Exception e){
e.printStackTrace();
}
return res;
}
//读取缓存文件内容,自动为文件名添加缓存路径
public static String getContentFromCacheFile(String filename){
return getContentFromFile(getCacheFileName(filename));
}
//将JSON保存到缓存文件中
//JSONObject、JSONArray自动识别
//自动为文件名添加缓存路径
//返回值: true - 成功 false - 失败
public static Boolean savejSONToCacheFile(Object JSON, String filename){
String content;
try{
JSONObject obj = (JSONObject)JSON;
content = obj.toString();
} catch(Exception e){
try{
JSONArray arr = (JSONArray)JSON;
content = arr.toString();
} catch(Exception e1){
return false;
}
}
return saveContentToFile(content, getCacheFileName(filename));
}
//从指定文件中获取JSONObject
public static JSONObject getJSONObjectFromFile(String filename){
try {
return new JSONObject(getContentFromFile(filename));
} catch (Exception e) {
return null;
}
}
//从指定缓存文件中获取JSONObject
//自动添加缓存路径
public static JSONObject getJSONObjectFromCacheFile(String filename){
return getJSONObjectFromFile(getCacheFileName(filename));
}
//从指定文件中获取JSONArray
public static JSONArray getJSONArrayFromFile(String filename){
try {
return new JSONArray(getContentFromFile(filename));
} catch (Exception e) {
return null;
}
}
//从指定缓存文件中获取JSONArray
//自动添加缓存路径
public static JSONArray getJSONArrayFromCacheFile(String filename){
return getJSONArrayFromFile(getCacheFileName(filename));
}
//直接获取用户id(手机号)
public static String getUserId(){
try{
SharedPreferences userinfo = applicationContext.getSharedPreferences(
LoginActivity.PREFS_PRIVATE, Context.MODE_PRIVATE);
return userinfo.getString("userid", "");
} catch (Exception e){
return "";
}
}
private static String getUserProfileName(){
// String cacheDir = getFilesDir().getAbsolutePath();
String userId = getUserId();
// return cacheDir + "/" + userId + ".json";
return getCacheFileName(userId + ".json");
}
//直接获取用户等级
public static String getUserLevel(){
try{
JSONObject json = getJSONObjectFromFile(getUserProfileName());
return json.getString("member_level");
} catch (Exception e){
return "0";
}
}
//本地保存用户等级
public static void saveUserLevel(String level){
try{
JSONObject json = getJSONObjectFromFile(getUserProfileName());
json.put("member_level", level);
saveContentToFile(json.toString(), getUserProfileName());
} catch (Exception e){
//do nothing
}
}
//将学分View中的学分减掉deltaPoints的学分显示
//自动判定,当新学分小于等于0时不显示
public static void changePointTextviewByDeltaPoint(TextView pointTextView,
int deltaPoints){
int point = getPointFromPointText(pointTextView.getText().toString()) - deltaPoints;
String newPoint = getFinalPointString(point);
pointTextView.setText(newPoint);
if (newPoint.equals(STRING_NO_POINT)){
pointTextView.setVisibility(View.GONE);
} else{
pointTextView.setVisibility(View.VISIBLE);
}
}
//自动为学分字符串前添加“+”
//无论学分字符串之前是否有“+”
//如果学分小于等于0,则返回Utils.STRING_NO_POINTS
public static String getFinalPointString(String pointString){
int point = getPointFromPointText(pointString);
return getFinalPointString(point);
}
//将学分数值转换为带“+”的学分字符串
//如果学分小于等于0,则返回Utils.STRING_NO_POINTS
public static String getFinalPointString(int point){
if (point > 0){
return "+" + point;
} else{
return STRING_NO_POINT;
}
}
//将学分字符串转换为数值
public static int getPointFromPointText(String pointText){
try {
if (pointText.startsWith("+")){
pointText = pointText.substring(1);
}
return Integer.valueOf(pointText).intValue();
} catch (Exception e) {
return 0;
}
}
//根据文章等级与店员等级判定返回指定文章JSON中的目标url
public static String getFinalUrl(JSONObject articleJSON){
String url = "";
try {
if (articleJSON.has("url")){
url = articleJSON.getString("url");
}
int articleLevel = LEVEL_INTERN;
if (articleJSON.has("content_level")){
String contentLevel = articleJSON.getString("content_level");
articleLevel = Integer.valueOf(contentLevel).intValue();
}
int userLevel = Integer.valueOf(getUserLevel()).intValue();
if (articleLevel >= LEVEL_LICENSED_PHARMACIST && userLevel < LEVEL_LICENSED_PHARMACIST){
return "yaoxin://lpharmacist/confirm";
} else if (articleLevel >= LEVEL_PHARMACIST && userLevel < LEVEL_PHARMACIST){
return "yaoxin://pharmacist/confirm";
} else if (articleLevel >= LEVEL_NORMAL && userLevel < LEVEL_NORMAL){
return "yaoxin://userlevel";
} else{
return url;
}
} catch (Exception e) {
return url;
}
}
//判定字符串是否是JSONObject或JSONArray
public static boolean isJSON(String content) {
try {
new JSONObject(content);
} catch (JSONException e) {
try {
new JSONArray(content);
} catch (JSONException c) {
return false;
}
}
return true;
}
//从JSONArray中移除指定序号的item
public static void removeJSONArrayItem(int index, JSONArray json) throws Exception{
if(index < 0)
return;
Field valuesField=JSONArray.class.getDeclaredField("values");
valuesField.setAccessible(true);
List
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.List;
import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class Utils {
public static final String STRING_NO_POINT = "";
public static Context applicationContext;
public static final int LEVEL_INTERN = 0;
public static final int LEVEL_NORMAL = 1;
public static final int LEVEL_PHARMACIST = 6;
public static final int LEVEL_LICENSED_PHARMACIST = 7;
/**
* 检测是否有可用网络
*
* @param context
* @return 网络连接状态
*/
public static boolean isNetworkAvailable(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// 获取网络信息
NetworkInfo info = cm.getActiveNetworkInfo();
// 返回检测的网络状态
return (info != null && info.isConnected() && info.isAvailable());
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static boolean isWifiConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWiFiNetworkInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWiFiNetworkInfo != null) {
return mWiFiNetworkInfo.isAvailable();
}
}
return false;
}
public static boolean isMobileConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mMobileNetworkInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mMobileNetworkInfo != null) {
return mMobileNetworkInfo.isAvailable();
}
}
return false;
}
/*
* 获取当前的网络状态 -1:没有网络 1:WIFI网络 2:wap网络 3:net网络
*
* */
public static int getConnectedType(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager
.getActiveNetworkInfo();
if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
return mNetworkInfo.getType();
}
}
return -1;
}
//获取缓存文件名
public static String getCacheFileName(String filename){
String cacheDir = applicationContext.getFilesDir().getAbsolutePath();
if (filename.startsWith("/")){
return cacheDir + filename;
} else{
return cacheDir + "/" + filename;
}
}
//将String内容保存到文件中
//返回值: true - 成功 false - 失败
public static Boolean saveContentToFile(String content, String filename){
try{
File f = new File(filename);
if (!f.exists()){
f.getParentFile().mkdirs();
f.createNewFile();
}
FileOutputStream ofile = new FileOutputStream(f);
ofile.write(content.getBytes());
ofile.close();
return true;
} catch (Exception e){
return false;
}
}
//将String内容保存到缓存文件中,自动为filename文件名添加缓存路径
//返回值: true - 成功 false - 失败
public static Boolean saveStringToCacheFile(String content, String filename){
return saveContentToFile(content, getCacheFileName(filename));
}
//读取文件内容
public static String getContentFromFile(String filename){
String res = "";
try{
FileInputStream fin = new FileInputStream(filename);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}
catch(Exception e){
e.printStackTrace();
}
return res;
}
//读取缓存文件内容,自动为文件名添加缓存路径
public static String getContentFromCacheFile(String filename){
return getContentFromFile(getCacheFileName(filename));
}
//将JSON保存到缓存文件中
//JSONObject、JSONArray自动识别
//自动为文件名添加缓存路径
//返回值: true - 成功 false - 失败
public static Boolean savejSONToCacheFile(Object JSON, String filename){
String content;
try{
JSONObject obj = (JSONObject)JSON;
content = obj.toString();
} catch(Exception e){
try{
JSONArray arr = (JSONArray)JSON;
content = arr.toString();
} catch(Exception e1){
return false;
}
}
return saveContentToFile(content, getCacheFileName(filename));
}
//从指定文件中获取JSONObject
public static JSONObject getJSONObjectFromFile(String filename){
try {
return new JSONObject(getContentFromFile(filename));
} catch (Exception e) {
return null;
}
}
//从指定缓存文件中获取JSONObject
//自动添加缓存路径
public static JSONObject getJSONObjectFromCacheFile(String filename){
return getJSONObjectFromFile(getCacheFileName(filename));
}
//从指定文件中获取JSONArray
public static JSONArray getJSONArrayFromFile(String filename){
try {
return new JSONArray(getContentFromFile(filename));
} catch (Exception e) {
return null;
}
}
//从指定缓存文件中获取JSONArray
//自动添加缓存路径
public static JSONArray getJSONArrayFromCacheFile(String filename){
return getJSONArrayFromFile(getCacheFileName(filename));
}
//直接获取用户id(手机号)
public static String getUserId(){
try{
SharedPreferences userinfo = applicationContext.getSharedPreferences(
LoginActivity.PREFS_PRIVATE, Context.MODE_PRIVATE);
return userinfo.getString("userid", "");
} catch (Exception e){
return "";
}
}
private static String getUserProfileName(){
// String cacheDir = getFilesDir().getAbsolutePath();
String userId = getUserId();
// return cacheDir + "/" + userId + ".json";
return getCacheFileName(userId + ".json");
}
//直接获取用户等级
public static String getUserLevel(){
try{
JSONObject json = getJSONObjectFromFile(getUserProfileName());
return json.getString("member_level");
} catch (Exception e){
return "0";
}
}
//本地保存用户等级
public static void saveUserLevel(String level){
try{
JSONObject json = getJSONObjectFromFile(getUserProfileName());
json.put("member_level", level);
saveContentToFile(json.toString(), getUserProfileName());
} catch (Exception e){
//do nothing
}
}
//将学分View中的学分减掉deltaPoints的学分显示
//自动判定,当新学分小于等于0时不显示
public static void changePointTextviewByDeltaPoint(TextView pointTextView,
int deltaPoints){
int point = getPointFromPointText(pointTextView.getText().toString()) - deltaPoints;
String newPoint = getFinalPointString(point);
pointTextView.setText(newPoint);
if (newPoint.equals(STRING_NO_POINT)){
pointTextView.setVisibility(View.GONE);
} else{
pointTextView.setVisibility(View.VISIBLE);
}
}
//自动为学分字符串前添加“+”
//无论学分字符串之前是否有“+”
//如果学分小于等于0,则返回Utils.STRING_NO_POINTS
public static String getFinalPointString(String pointString){
int point = getPointFromPointText(pointString);
return getFinalPointString(point);
}
//将学分数值转换为带“+”的学分字符串
//如果学分小于等于0,则返回Utils.STRING_NO_POINTS
public static String getFinalPointString(int point){
if (point > 0){
return "+" + point;
} else{
return STRING_NO_POINT;
}
}
//将学分字符串转换为数值
public static int getPointFromPointText(String pointText){
try {
if (pointText.startsWith("+")){
pointText = pointText.substring(1);
}
return Integer.valueOf(pointText).intValue();
} catch (Exception e) {
return 0;
}
}
//根据文章等级与店员等级判定返回指定文章JSON中的目标url
public static String getFinalUrl(JSONObject articleJSON){
String url = "";
try {
if (articleJSON.has("url")){
url = articleJSON.getString("url");
}
int articleLevel = LEVEL_INTERN;
if (articleJSON.has("content_level")){
String contentLevel = articleJSON.getString("content_level");
articleLevel = Integer.valueOf(contentLevel).intValue();
}
int userLevel = Integer.valueOf(getUserLevel()).intValue();
if (articleLevel >= LEVEL_LICENSED_PHARMACIST && userLevel < LEVEL_LICENSED_PHARMACIST){
return "yaoxin://lpharmacist/confirm";
} else if (articleLevel >= LEVEL_PHARMACIST && userLevel < LEVEL_PHARMACIST){
return "yaoxin://pharmacist/confirm";
} else if (articleLevel >= LEVEL_NORMAL && userLevel < LEVEL_NORMAL){
return "yaoxin://userlevel";
} else{
return url;
}
} catch (Exception e) {
return url;
}
}
//判定字符串是否是JSONObject或JSONArray
public static boolean isJSON(String content) {
try {
new JSONObject(content);
} catch (JSONException e) {
try {
new JSONArray(content);
} catch (JSONException c) {
return false;
}
}
return true;
}
//从JSONArray中移除指定序号的item
public static void removeJSONArrayItem(int index, JSONArray json) throws Exception{
if(index < 0)
return;
Field valuesField=JSONArray.class.getDeclaredField("values");
valuesField.setAccessible(true);
List