缓存工具类
public class ACache {
public static final int TIME_HOUR = 60 * 60;//
public static final int TIME_DAY = TIME_HOUR * 24;
private static final int MAX_SIZE = 1000 * 1000 * 50; // 50 mb
private static final int MAX_COUNT = Integer.MAX_VALUE; // 不限制存放数据的数量
private static Map<String, ACache> mInstanceMap = new HashMap<String, ACache>();
private ACacheManager mCache;
public static ACache get(Context ctx) {
return get(ctx, "ACache");
}
public static ACache get(Context ctx, String cacheName) {
File f = new File(ctx.getCacheDir(), cacheName);
return get(f, MAX_SIZE, MAX_COUNT);
}
public static ACache get(File cacheDir) {
return get(cacheDir, MAX_SIZE, MAX_COUNT);
}
public static ACache get(Context ctx, long max_zise, int max_count) {
File f = new File(ctx.getCacheDir(), "ACache");
return get(f, max_zise, max_count);
}
public static ACache get(File cacheDir, long max_zise, int max_count) {
ACache manager = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid());
if (manager == null) {
manager = new ACache(cacheDir, max_zise, max_count);
mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager);
}
return manager;
}
private static String myPid() {
return "_" + android.os.Process.myPid();
}
private ACache(File cacheDir, long max_size, int max_count) {
if (!cacheDir.exists() && !cacheDir.mkdirs()) {
throw new RuntimeException("can't make dirs in "
+ cacheDir.getAbsolutePath());
}
mCache = new ACacheManager(cacheDir, max_size, max_count);
}
// =======================================
// ============ String数据 读写 ==============
// =======================================
/**
* 保存 String数据 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的String数据
*/
public void put(String key, String value) {
File file = mCache.newFile(key);
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(file), 1024);
out.write(value);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mCache.put(file);
}
}
/**
* 保存 String数据 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的String数据
* @param saveTime
* 保存的时间,单位:秒
*/
public void put(String key, String value, int saveTime) {
put(key, Utils.newStringWithDateInfo(saveTime, value));
}
/**
* 读取 String数据
*
* @param key
* @return String 数据
*/
public String getAsString(String key) {
File file = mCache.get(key);
if (!file.exists())
return null;
boolean removeFile = false;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
String readString = "";
String currentLine;
while ((currentLine = in.readLine()) != null) {
readString += currentLine;
}
if (!Utils.isDue(readString)) {
return Utils.clearDateInfo(readString);
} else {
removeFile = true;
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (removeFile)
remove(key);
}
}
// =======================================
// ============= JSONObject 数据 读写 ==============
// =======================================
/**
* 保存 JSONObject数据 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的JSON数据
*/
public void put(String key, JSONObject value) {
put(key, value.toString());
}
/**
* 保存 JSONObject数据 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的JSONObject数据
* @param saveTime
* 保存的时间,单位:秒
*/
public void put(String key, JSONObject value, int saveTime) {
put(key, value.toString(), saveTime);
}
/**
* 读取JSONObject数据
*
* @param key
* @return JSONObject数据
*/
public JSONObject getAsJSONObject(String key) {
String JSONString = getAsString(key);
try {
JSONObject obj = new JSONObject(JSONString);
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// =======================================
// ============ JSONArray 数据 读写 =============
// =======================================
/**
* 保存 JSONArray数据 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的JSONArray数据
*/
public void put(String key, JSONArray value) {
put(key, value.toString());
}
/**
* 保存 JSONArray数据 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的JSONArray数据
* @param saveTime
* 保存的时间,单位:秒
*/
public void put(String key, JSONArray value, int saveTime) {
put(key, value.toString(), saveTime);
}
/**
* 读取JSONArray数据
*
* @param key
* @return JSONArray数据
*/
public JSONArray getAsJSONArray(String key) {
String JSONString = getAsString(key);
try {
JSONArray obj = new JSONArray(JSONString);
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// =======================================
// ============== byte 数据 读写 =============
// =======================================
/**
* 保存 byte数据 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的数据
*/
public void put(String key, byte[] value) {
File file = mCache.newFile(key);
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mCache.put(file);
}
}
/**
* 保存 byte数据 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的数据
* @param saveTime
* 保存的时间,单位:秒
*/
public void put(String key, byte[] value, int saveTime) {
put(key, Utils.newByteArrayWithDateInfo(saveTime, value));
}
/**
* 获取 byte 数据
*
* @param key
* @return byte 数据
*/
public byte[] getAsBinary(String key) {
RandomAccessFile RAFile = null;
boolean removeFile = false;
try {
File file = mCache.get(key);
if (!file.exists())
return null;
RAFile = new RandomAccessFile(file, "r");
byte[] byteArray = new byte[(int) RAFile.length()];
RAFile.read(byteArray);
if (!Utils.isDue(byteArray)) {
return Utils.clearDateInfo(byteArray);
} else {
removeFile = true;
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (RAFile != null) {
try {
RAFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (removeFile)
remove(key);
}
}
// =======================================
// ============= 序列化 数据 读写 ===============
// =======================================
/**
* 保存 Serializable数据 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的value
*/
public void put(String key, Serializable value) {
put(key, value, -1);
}
/**
* 保存 Serializable数据到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的value
* @param saveTime
* 保存的时间,单位:秒
*/
public void put(String key, Serializable value, int saveTime) {
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(value);
byte[] data = baos.toByteArray();
if (saveTime != -1) {
put(key, data, saveTime);
} else {
put(key, data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException e) {
}
}
}
/**
* 读取 Serializable数据
*
* @param key
* @return Serializable 数据
*/
public Object getAsObject(String key) {
byte[] data = getAsBinary(key);
if (data != null) {
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
bais = new ByteArrayInputStream(data);
ois = new ObjectInputStream(bais);
Object reObject = ois.readObject();
return reObject;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (bais != null)
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (ois != null)
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
// =======================================
// ============== bitmap 数据 读写 =============
// =======================================
/**
* 保存 bitmap 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的bitmap数据
*/
public void put(String key, Bitmap value) {
put(key, Utils.Bitmap2Bytes(value));
}
/**
* 保存 bitmap 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的 bitmap 数据
* @param saveTime
* 保存的时间,单位:秒
*/
public void put(String key, Bitmap value, int saveTime) {
put(key, Utils.Bitmap2Bytes(value), saveTime);
}
/**
* 读取 bitmap 数据
*
* @param key
* @return bitmap 数据
*/
public Bitmap getAsBitmap(String key) {
if (getAsBinary(key) == null) {
return null;
}
return Utils.Bytes2Bimap(getAsBinary(key));
}
// =======================================
// ============= drawable 数据 读写 =============
// =======================================
/**
* 保存 drawable 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的drawable数据
*/
public void put(String key, Drawable value) {
put(key, Utils.drawable2Bitmap(value));
}
/**
* 保存 drawable 到 缓存中
*
* @param key
* 保存的key
* @param value
* 保存的 drawable 数据
* @param saveTime
* 保存的时间,单位:秒
*/
public void put(String key, Drawable value, int saveTime) {
put(key, Utils.drawable2Bitmap(value), saveTime);
}
/**
* 读取 Drawable 数据
*
* @param key
* @return Drawable 数据
*/
public Drawable getAsDrawable(String key) {
if (getAsBinary(key) == null) {
return null;
}
return Utils.bitmap2Drawable(Utils.Bytes2Bimap(getAsBinary(key)));
}
/**
* 获取缓存文件
*
* @param key
* @return value 缓存的文件
*/
public File file(String key) {
File f = mCache.newFile(key);
if (f.exists())
return f;
return null;
}
/**
* 移除某个key
*
* @param key
* @return 是否移除成功
*/
public boolean remove(String key) {
return mCache.remove(key);
}
/**
* 清除所有数据
*/
public void clear() {
mCache.clear();
}
/**
* @title 缓存管理器
*/
public class ACacheManager {
private final AtomicLong cacheSize;
private final AtomicInteger cacheCount;
private final long sizeLimit;
private final int countLimit;
private final Map<File, Long> lastUsageDates = Collections
.synchronizedMap(new HashMap<File, Long>());
protected File cacheDir;
private ACacheManager(File cacheDir, long sizeLimit, int countLimit) {
this.cacheDir = cacheDir;
this.sizeLimit = sizeLimit;
this.countLimit = countLimit;
cacheSize = new AtomicLong();
cacheCount = new AtomicInteger();
calculateCacheSizeAndCacheCount();
}
/**
* 计算 cacheSize和cacheCount
*/
private void calculateCacheSizeAndCacheCount() {
new Thread(new Runnable() {
@Override
public void run() {
int size = 0;
int count = 0;
File[] cachedFiles = cacheDir.listFiles();
if (cachedFiles != null) {
for (File cachedFile : cachedFiles) {
size += calculateSize(cachedFile);
count += 1;
lastUsageDates.put(cachedFile,
cachedFile.lastModified());
}
cacheSize.set(size);
cacheCount.set(count);
}
}
}).start();
}
private void put(File file) {
int curCacheCount = cacheCount.get();
while (curCacheCount + 1 > countLimit) {
long freedSize = removeNext();
cacheSize.addAndGet(-freedSize);
curCacheCount = cacheCount.addAndGet(-1);
}
cacheCount.addAndGet(1);
long valueSize = calculateSize(file);
long curCacheSize = cacheSize.get();
while (curCacheSize + valueSize > sizeLimit) {
long freedSize = removeNext();
curCacheSize = cacheSize.addAndGet(-freedSize);
}
cacheSize.addAndGet(valueSize);
Long currentTime = System.currentTimeMillis();
file.setLastModified(currentTime);
lastUsageDates.put(file, currentTime);
}
private File get(String key) {
File file = newFile(key);
Long currentTime = System.currentTimeMillis();
file.setLastModified(currentTime);
lastUsageDates.put(file, currentTime);
return file;
}
private File newFile(String key) {
return new File(cacheDir, key.hashCode() + "");
}
private boolean remove(String key) {
File image = get(key);
return image.delete();
}
private void clear() {
lastUsageDates.clear();
cacheSize.set(0);
File[] files = cacheDir.listFiles();
if (files != null) {
for (File f : files) {
f.delete();
}
}
}
/**
* 移除旧的文件
*
* @return
*/
private long removeNext() {
if (lastUsageDates.isEmpty()) {
return 0;
}
Long oldestUsage = null;
File mostLongUsedFile = null;
Set<Entry<File, Long>> entries = lastUsageDates.entrySet();
synchronized (lastUsageDates) {
for (Entry<File, Long> entry : entries) {
if (mostLongUsedFile == null) {
mostLongUsedFile = entry.getKey();
oldestUsage = entry.getValue();
} else {
Long lastValueUsage = entry.getValue();
if (lastValueUsage < oldestUsage) {
oldestUsage = lastValueUsage;
mostLongUsedFile = entry.getKey();
}
}
}
}
long fileSize = calculateSize(mostLongUsedFile);
if (mostLongUsedFile.delete()) {
lastUsageDates.remove(mostLongUsedFile);
}
return fileSize;
}
private long calculateSize(File file) {
return file.length();
}
}
/**
* @title 时间计算工具类
*/
private static class Utils {
/**
* 判断缓存的String数据是否到期
*
* @param str
* @return true:到期了 false:还没有到期
*/
private static boolean isDue(String str) {
return isDue(str.getBytes());
}
/**
* 判断缓存的byte数据是否到期
* @param data
* @return true:到期了 false:还没有到期
*/
private static boolean isDue(byte[] data) {
String[] strs = getDateInfoFromDate(data);
if (strs != null && strs.length == 2) {
String saveTimeStr = strs[0];
while (saveTimeStr.startsWith("0")) {
saveTimeStr = saveTimeStr
.substring(1, saveTimeStr.length());
}
long saveTime = Long.valueOf(saveTimeStr);
long deleteAfter = Long.valueOf(strs[1]);
if (System.currentTimeMillis() > saveTime + deleteAfter * 1000) {
return true;
}
}
return false;
}
private static String newStringWithDateInfo(int second, String strInfo) {
return createDateInfo(second) + strInfo;
}
private static byte[] newByteArrayWithDateInfo(int second, byte[] data2) {
byte[] data1 = createDateInfo(second).getBytes();
byte[] retdata = new byte[data1.length + data2.length];
System.arraycopy(data1, 0, retdata, 0, data1.length);
System.arraycopy(data2, 0, retdata, data1.length, data2.length);
return retdata;
}
private static String clearDateInfo(String strInfo) {
if (strInfo != null && hasDateInfo(strInfo.getBytes())) {
strInfo = strInfo.substring(strInfo.indexOf(mSeparator) + 1,
strInfo.length());
}
return strInfo;
}
private static byte[] clearDateInfo(byte[] data) {
if (hasDateInfo(data)) {
return copyOfRange(data, indexOf(data, mSeparator) + 1,
data.length);
}
return data;
}
private static boolean hasDateInfo(byte[] data) {
return data != null && data.length > 15 && data[13] == '-'
&& indexOf(data, mSeparator) > 14;
}
private static String[] getDateInfoFromDate(byte[] data) {
if (hasDateInfo(data)) {
String saveDate = new String(copyOfRange(data, 0, 13));
String deleteAfter = new String(copyOfRange(data, 14,
indexOf(data, mSeparator)));
return new String[] { saveDate, deleteAfter };
}
return null;
}
private static int indexOf(byte[] data, char c) {
for (int i = 0; i < data.length; i++) {
if (data[i] == c) {
return i;
}
}
return -1;
}
private static byte[] copyOfRange(byte[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
byte[] copy = new byte[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
private static final char mSeparator = ' ';
private static String createDateInfo(int second) {
String currentTime = System.currentTimeMillis() + "";
while (currentTime.length() < 13) {
currentTime = "0" + currentTime;
}
return currentTime + "-" + second + mSeparator;
}
/*
* Bitmap → byte[]
*/
private static byte[] Bitmap2Bytes(Bitmap bm) {
if (bm == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/*
* byte[] → Bitmap
*/
private static Bitmap Bytes2Bimap(byte[] b) {
if (b.length == 0) {
return null;
}
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
/*
* Drawable → Bitmap
*/
private static Bitmap drawable2Bitmap(Drawable drawable) {
if (drawable == null) {
return null;
}
// 取 drawable 的长宽
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
// 取 drawable 的颜色格式
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
// 建立对应 bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 建立对应 bitmap 的画布
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 把 drawable 内容画到画布中
drawable.draw(canvas);
return bitmap;
}
/*
* Bitmap → Drawable
*/
@SuppressWarnings("deprecation")
private static Drawable bitmap2Drawable(Bitmap bm) {
if (bm == null) {
return null;
}
return new BitmapDrawable(bm);
}
}
}
Acitity工具类
public class ActivityUtil {
/**
* 开启另外一个activity
*
* @param activity
* @param cls 另外的activity类
* @param bundle 传递的bundle对象
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivity(Activity activity, Class<?> cls, Bundle bundle, boolean isFinish) {
Intent intent = new Intent(activity, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivity(intent);
if (isFinish) {
activity.finish();
}
activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
/**
* 开启另外一个activity(默认动画)
*
* @param activity
* @param cls 另外的activity类
* @param bundle 传递的bundle对象
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivityDefault(Activity activity, Class<?> cls, Bundle bundle, boolean isFinish) {
Intent intent = new Intent(activity, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivity(intent);
if (isFinish) {
activity.finish();
}
}
/**
* 开启另外一个activity
*
* @param activity
* @param cls 另外的activity类
* @param bundle 传递的bundle对象
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivityBack(Activity activity, Class<?> cls, Bundle bundle, boolean isFinish) {
Intent intent = new Intent(activity, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivity(intent);
if (isFinish) {
activity.finish();
}
activity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
/**
* 开启另外一个activity
*
* @param activity
* @param cls 另外的activity类
* @param bundle 传递的bundle对象
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivityForResult(Activity activity, Class<?> cls, int requestCode,
Bundle bundle, boolean isFinish) {
Intent intent = new Intent(activity, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivityForResult(intent, requestCode);
if (isFinish) {
activity.finish();
}
activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
/**
* Fragment中开启另外一个activity
*
* @param fragment
* @param cls 另外的activity类
* @param bundle 传递的bundle对象
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivityForResult(Fragment fragment, Class<?> cls, int requestCode,
Bundle bundle, boolean isFinish) {
Intent intent = new Intent(fragment.getActivity(), cls);
if (bundle != null) {
intent.putExtras(bundle);
}
fragment.startActivityForResult(intent, requestCode);
if (isFinish) {
fragment.getActivity().finish();
}
fragment.getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
/**
* 开启另外一个activity
*
* @param activity
* @param intent
* @param bundle 传递的bundle对象
* @param requestCode
* @param isFinish true表示要关闭activity false表示不要关闭activity
*/
public static void startActivityForResultIntent(Activity activity, Intent intent,
Bundle bundle, int requestCode, boolean isFinish) {
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivityForResult(intent, requestCode);
if (isFinish) {
activity.finish();
}
activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
public static void finishActivity(Activity activity){
// 退出Activity时动画
activity.finish();
activity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
/**
* 进入创建直播界面
* @param activity
* @param cls
* @param bundle
* @param isFinish
*/
public static void startCreateLiveActivity(Activity activity, Class cls, Bundle bundle, boolean isFinish) {
Intent intent = new Intent(activity, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
activity.startActivity(intent);
if (isFinish) {
activity.finish();
}
activity.overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
}
}
屏幕系统工具类
public class BaseTools {
/** 获取屏幕宽度*/
public final static int getWindowsWidth(Activity activity) {
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
return dm.widthPixels;
}
/** 获取屏幕高度 */
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
/** 弹出系统软键盘*/
public static void showSoftKeyBoard(final View view) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
InputMethodManager m = (InputMethodManager) view.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 200);
}
public static String replaceHtml(String content){
content = content.replace("<em>", "");
content = content.replace("</em>", "");
content = content.replace("<br>", "\n");
content = content.replace("</br>", "");
content = content.replace(" ", " ");
content = content.replace("<div>", "\n");
content = content.replace("</div>", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
content = content.replace(" ", " ");
content = content.replace(" ", " ");
content = content.replace(" ", " ");
content = content.replace("", " ");
content = content.replace("", " ");
content = content.replace("", " ");
content = content.replace("", " ");
content = content.replace("–", "-");
content = content.replace("—", "_");
content = content.replace("‘", "'");
content = content.replace("’", "'");
content = content.replace("‚", ",");
content = content.replace("“", "'");
content = content.replace("”", "'");
content = content.replace("„", ",,");
content = content.replace("†", "+");
content = content.replace("‡", "++");
content = content.replace("‰", "%");
content = content.replace("‹", "<");
content = content.replace("›", ">");
content = content.replace("€", "E");
return content;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List<NewDetail> removeDuplicate(List<NewDetail> list) {
Set set = new LinkedHashSet<NewDetail>();
set.addAll(list);
list.clear();
list.addAll(set);
return list;
}
}
解析工具类
public class BeanUtils {
public static List<PushBean> pushBean1(String jsonString) {
List<PushBean> list = new ArrayList<PushBean>();
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken<List<PushBean>>() {
}.getType());
return list;
}
public static PushBean pushBean(String jsonString) {
Gson gson = new Gson();
PushBean login = new PushBean();
login = gson.fromJson(jsonString, PushBean.class);
return login;
}
public static NewsJson newsBean(String jsonStirng){
Gson gson = new Gson();
NewsJson newsJson = new NewsJson();
try {
newsJson = gson.fromJson(jsonStirng, NewsJson.class);
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newsJson;
}
public static ChannelItems channelItemBean (String josnString){
Gson gson = new Gson();
ChannelItems channelItems = new ChannelItems();
channelItems = gson.fromJson(josnString, ChannelItems.class);
return channelItems;
}
public static TopicBean topicBean(String josnString){
Gson gson = new Gson();
TopicBean topic = new TopicBean();
topic = gson.fromJson(josnString, TopicBean.class);
return topic;
}
}
公用工具类
public class CommonUtils {
/**
* 防止重复点击
*/
private static long lastClickTime;
public static boolean isFastDoubleClick() {
long time = System.currentTimeMillis();
long timeD = time - lastClickTime;
if (0 < timeD && timeD < 800) {
return true;
}
lastClickTime = time;
return false;
}
/**
* 弹出 登录提示框
*/
public static void showLoginDialog(Context context) {
SSOController ssoController = new SSOController();
final String ticket = ssoController.getInstance().getCacheTicket();
if (ticket != null && !ticket.equals("")) {
final AutoLoginDialog dialogidnumber = new AutoLoginDialog(context, R.style.Dialog);
final View viewDialogidnumber = (View) View.inflate(context, R.layout.alertdialog_autologin, null);
String phoneNames = ssoController.getCacheUser();
Button btn_positive = (Button) viewDialogidnumber.findViewById(R.id.btn_positive);
AutoLoginDialog.Builder buildername = new AutoLoginDialog.Builder(context, dialogidnumber);
buildername.setContentView(viewDialogidnumber).setTitle(
context.getString(R.string.phone_number_login) + phoneNames + context.getString(R.string.phone_islogin));
buildername.setPositiveButton(context.getString(R.string.phone_ok), new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
dialogidnumber.dismiss();
}
});
buildername.create().show();
}else {
Intent intent = new Intent(context, SSOLogin.class);
context.startActivity(intent);
}
}
/**
* 检测相机是否存在 s
*/
public static boolean isExistCamera(Context context) {
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
}
return false;
}
/**
* 裁剪图片
*/
public static void cutPhoto(Activity activity, Uri uri, boolean isHeadPic) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
intent.putExtra("crop", "true");
if (isHeadPic) {
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("scale", true);
// 只能设置成false,k920无法返回
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(FileUtil.getHeadPhotoFileTemp()));
intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
intent.putExtra("noFaceDetection", true);
} else {
// 是否保留比例
intent.putExtra("scale", "true");
intent.putExtra("output", Uri.fromFile(FileUtil.getWallPaperFile()));
}
ActivityUtil.startActivityForResultIntent(activity, intent, null,
RegistSecondActivity.ACTIVITY_MODIFY_PHOTO_REQUESTCODE, false);
}
public static boolean isLogin(Context context) {
boolean isLogin = false;
String login = (String) SpUtils.get(context, "news_token", "");
if (login != null && !login.equals("")) {
isLogin = true;
}
return isLogin;
}
// ticket == false ticket有票 ticket == true 没有票
public static boolean isTicket(SSOController ssoController){
boolean isticket = true;
final String ticket = ssoController.getInstance().getCacheTicket();
if( ticket !=null && !ticket.equals("")){
isticket = false;
}
return isticket;
}
public static void sendBroadcast(String str) {
AppApplication.getApp().sendBroadcast(new Intent(str));
}
public static void initData(Context context){
int mode = (Integer) SpUtils.get(context, "fontSize", -1);
if(mode==-1||mode==1){
context.setTheme(R.style.Theme_Small);
}else if(mode==2){
context.setTheme(R.style.Theme_Medium);
}else if(mode==3){
context.setTheme(R.style.Theme_Large);
}
}
@SuppressWarnings("deprecation")
public static void initWebData(Context context,WebSettings settings){
int mode = (Integer)SpUtils.get(context, "fontSize", -1);
if(mode == -1 && mode == 1){
settings.setTextSize(TextSize.NORMAL);
}else if(mode == 2){
settings.setTextSize(TextSize.LARGER);
}else if(mode == 3){
settings.setTextSize(TextSize.LARGEST);
}
}
}
网络广播工具类
public class ConnectionChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
Toast.makeText(context, "24554", Toast.LENGTH_LONG).show();
//改变背景或者 处理网络的全局变量
}else {
//改变背景或者 处理网络的全局变量
}
}
}
本应用数据清除管理器
public class DataCleanManager {
public static String getTotalCacheSize(Context context) throws Exception {
long cacheSize = getFolderSize(context.getCacheDir());
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cacheSize += getFolderSize(context.getExternalCacheDir());
}
return getFormatSize(cacheSize);
}
public static void clearAllCache(Context context) {
deleteDir(context.getCacheDir());
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
deleteDir(context.getExternalCacheDir());
}
}
private static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
/**
* * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * *
*
* @param context
*/
public static void cleanInternalCache(Context context) {
deleteFilesByDirectory(context.getCacheDir());
}
/**
* * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * *
*
* @param context
*/
public static void cleanDatabases(Context context) {
deleteFilesByDirectory(new File("/data/data/" + context.getPackageName() + "/databases"));
}
/**
* * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) *
*
* @param context
*/
public static void cleanSharedPreference(Context context) {
deleteFilesByDirectory(new File("/data/data/" + context.getPackageName() + "/shared_prefs"));
}
/**
* * 按名字清除本应用数据库 * *
*
* @param context
* @param dbName
*/
public static void cleanDatabaseByName(Context context, String dbName) {
context.deleteDatabase(dbName);
}
/**
* * 清除/data/data/com.xxx.xxx/files下的内容 * *
*
* @param context
*/
public static void cleanFiles(Context context) {
deleteFilesByDirectory(context.getFilesDir());
}
/**
* * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
*
* @param context
*/
public static void cleanExternalCache(Context context) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
deleteFilesByDirectory(context.getExternalCacheDir());
}
}
/**
* * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 * *
*
* @param filePath
*/
public static void cleanCustomCache(String filePath) {
deleteFilesByDirectory(new File(filePath));
}
/**
* * 清除本应用所有的数据 * *
*
* @param context
* @param filepath
*/
public static void cleanApplicationData(Context context, String... filepath) {
cleanInternalCache(context);
cleanExternalCache(context);
cleanDatabases(context);
cleanSharedPreference(context);
cleanFiles(context);
if (filepath == null) {
return;
}
for (String filePath : filepath) {
cleanCustomCache(filePath);
}
}
/**
* * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 * *
*
* @param directory
*/
private static void deleteFilesByDirectory(File directory) {
if (directory != null && directory.exists() && directory.isDirectory()) {
for (File item : directory.listFiles()) {
item.delete();
}
}
}
// 获取文件
// Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/
// 目录,一般放一些长时间保存的数据
// Context.getExternalCacheDir() -->
// SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据
public static long getFolderSize(File file) throws Exception {
long size = 0;
try {
File[] fileList = file.listFiles();
for (int i = 0; i < fileList.length; i++) {
// 如果下面还有文件
if (fileList[i].isDirectory()) {
size = size + getFolderSize(fileList[i]);
} else {
size = size + fileList[i].length();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return size;
}
/**
* 删除指定目录下文件及目录
*
* @param deleteThisPath
* @param filepath
* @return
*/
public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
if (!TextUtils.isEmpty(filePath)) {
try {
File file = new File(filePath);
if (file.isDirectory()) {// 如果下面还有文件
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFolderFile(files[i].getAbsolutePath(), true);
}
}
if (deleteThisPath) {
if (!file.isDirectory()) {// 如果是文件,删除
file.delete();
} else {// 目录
if (file.listFiles().length == 0) {// 目录下没有文件或者目录,删除
file.delete();
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 格式化单位
*
* @param size
* @return
*/
public static String getFormatSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
return size + "Byte";
}
double megaByte = kiloByte / 1024;
if (megaByte < 1) {
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
}
double gigaByte = megaByte / 1024;
if (gigaByte < 1) {
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
}
double teraBytes = gigaByte / 1024;
if (teraBytes < 1) {
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
}
public static String getCacheSize(File file) throws Exception {
return getFormatSize(getFolderSize(file));
}
}
时间工具类
public class DateTools {
/*
* 将时间戳转为字符串 ,格式:yyyy-MM-dd HH:mm
*/
public static String getStrTime_ymd_hm(String cc_time) {
String re_StrTime = "";
if (TextUtils.isEmpty(cc_time) || "null".equals(cc_time)) {
return re_StrTime;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
// 例如:cc_time=1291778220
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
/*
* 将时间戳转为字符串 ,格式:MM-dd HH:mm
*/
public static String getStrTime_md_hm(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
// 例如:cc_time=1291778220
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
/*
* 将时间戳转为字符串 ,格式:yyyy-MM-dd HH:mm:ss
*/
public static String getStrTime_ymd_hms(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 例如:cc_time=1291778220
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
/*
* 将时间戳转为字符串 ,格式:yyyy.MM.dd
*/
public static String getStrTime_ymd(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
// 例如:cc_time=1291778220
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
/*
* 将时间戳转为字符串 ,格式:yyyy
*/
public static String getStrTime_y(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
// 例如:cc_time=1291778220
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
/*
* 将时间戳转为字符串 ,格式:MM-dd
*/
public static String getStrTime_md(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
// 例如:cc_time=1291778220
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
/*
* 将时间戳转为字符串 ,格式:HH:mm
*/
public static String getStrTime_hm(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
// 例如:cc_time=1291778220
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
/*
* 将时间戳转为字符串 ,格式:HH:mm:ss
*/
public static String getStrTime_hms(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
// 例如:cc_time=1291778220
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
/*
* 将时间戳转为字符串 ,格式:MM-dd HH:mm:ss
*/
public static String getNewsDetailsDate(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
// 例如:cc_time=1291778220
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
public static String getData10(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyddHHmmss");
// 例如:cc_time=1291778220
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
/*
* 将字符串转为时间戳
*/
public static String getTime() {
String re_time = null;
long currentTime = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
Date d;
d = new Date(currentTime);
long l = d.getTime();
String str = String.valueOf(l);
re_time = str.substring(0, 10);
return re_time;
}
/*
* 将时间戳转为字符串 ,格式:yyyy.MM.dd 星期几
*/
public static String getSection(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd EEEE");
// 对于创建SimpleDateFormat传入的参数:EEEE代表星期,如“星期四”;MMMM代表中文月份,如“十一月”;MM代表月份,如“11”;
// yyyy代表年份,如“2010”;dd代表天,如“25”
// 例如:cc_time=1291778220
long lcc_time = Long.valueOf(cc_time);
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
/*
* 根据发布时间的不同返回不同的字符串 1.一小时以内显示分钟数 2.一小时以上12小时以内显示 小时数 3.大于12小时显示 MM-dd HH:mm
*/
public static String getBefitTimeString(String cc_time) {
String re_StrTime = null;
SimpleDateFormat sdf;
long lcc_time = Long.valueOf(cc_time);
long currentTime = System.currentTimeMillis();
long time = currentTime - lcc_time * 1000L;
if (time >= 0) {
if (3600000 > time) {
// re_StrTime = (currentTime - lcc_time ) / 60000 + "分钟前";
re_StrTime = (int) Math.ceil((time) / 60000) + "分钟前";
return re_StrTime;
} else if (3600000 <= time && time < 3600000 * 12) {
// re_StrTime = (currentTime - lcc_time ) / 3600000 + "小时前";
re_StrTime = (int) Math.ceil((time) / 3600000) + "个小时前";
return re_StrTime;
} else if (time >= 3600000 * 12 && time < 3600000 * 24 * 365) {
sdf = new SimpleDateFormat("MM-dd HH:mm");
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
} else {
sdf = new SimpleDateFormat("yyyy-MM-dd");
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
return re_StrTime;
}
} else {
sdf = new SimpleDateFormat("yyyy-MM-dd");
re_StrTime = sdf.format(new Date(lcc_time * 1000L));
}
return re_StrTime;
}
// public static String getTodayDate(){
// SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
// String nowTime=format.format(new Date());
// return
// }
}
动画工具类
public class LoadingAinm {
public static void ininLodingView(View view) {
ImageView loadingImageView = (ImageView) view
.findViewById(R.id.lodding);
TextView loadingTextView = (TextView) view
.findViewById(R.id.lodiing_text);
loadingImageView.setBackgroundResource(R.anim.anim_lodding);
final AnimationDrawable animationDrawable = (AnimationDrawable) loadingImageView
.getBackground();
loadingImageView.post(new Runnable() {
@Override
public void run() {
animationDrawable.start();
}
});
}
public static void ininLoding(Activity activity) {
ImageView loadingImageView = (ImageView) activity
.findViewById(R.id.lodding);
TextView loadingTextView = (TextView) activity
.findViewById(R.id.lodiing_text);
loadingImageView.setBackgroundResource(R.anim.anim_lodding);
final AnimationDrawable animationDrawable = (AnimationDrawable) loadingImageView
.getBackground();
loadingImageView.post(new Runnable() {
@Override
public void run() {
animationDrawable.start();
}
});
}
}
MD5工具类
public class MD5 {
private static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public final static String Md5Encode(String data) {
if (TextUtils.isEmpty(data))
return "";
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return data;
}
try {
byte[] bytes = md5.digest(data.getBytes("utf8"));
StringBuilder ret = new StringBuilder(bytes.length << 1);
for (int i = 0; i < bytes.length; i++) {
ret.append(Character.forDigit((bytes[i] >> 4) & 0xf, 16));
ret.append(Character.forDigit(bytes[i] & 0xf, 16));
}
return ret.toString();
} catch (UnsupportedEncodingException e) {
return data;
}
}
public final static String Md5FileEncode(String fileName) {
FileInputStream fis = null;
byte[] buf = new byte[4096];
MessageDigest md;
boolean fileIsNull = true;
try {
fis = new FileInputStream(fileName);
int len = 0;
md = MessageDigest.getInstance("MD5");
len = fis.read(buf);
if (len > 0) {
fileIsNull = false;
while (len > 0) {
md.update(buf, 0, len);
len = fis.read(buf);
}
}
} catch (Exception e) {
e.printStackTrace();
return "";
}
finally{
if(fis !=null){
try {
fis.close();
} catch (IOException e) {
}
}
}
if (fileIsNull) {
return "";
} else {
byte[] result = md.digest();
return bufferToHex(result);
}
}
private static String bufferToHex(byte bytes[]) {
return bufferToHex(bytes, 0, bytes.length);
}
private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
char c0 = hexDigits[(bt & 0xf0) >> 4];
char c1 = hexDigits[bt & 0xf];
stringbuffer.append(c0);
stringbuffer.append(c1);
}
private static String bufferToHex(byte bytes[], int m, int n) {
StringBuffer stringbuffer = new StringBuffer(2 * n);
int k = m + n;
for (int l = m; l < k; l++) {
appendHexPair(bytes[l], stringbuffer);
}
return stringbuffer.toString();
}
}
public class Md5Utils {
/***
* MD5加码 生成32位md5码
*/
public static String string2MD5(String inStr){
MessageDigest md5 = null;
try{
md5 = MessageDigest.getInstance("MD5");
}catch (Exception e){
System.out.println(e.toString());
e.printStackTrace();
return "";
}
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++){
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 某篇文章的评论列表
* md5(_appid+keyid+_key+私钥),私钥:BDTTtaID
* @param appid 4
* @param keyid 内容索引ID 可以是栏目cid和内容id组合,例如:1-10
* @param key 当前时间戳
* */
public static String listKey(String appid,String keyid,String key){
return string2MD5(appid+keyid+key+"BDTTtaID");
}
/**
* 发布评论
* md5(_appid+keyid+_key+username+私钥),私钥:BDTTtaID
* @param appid 4
* @param keyid 内容索引ID 可以是栏目cid和内容id组合,例如:1-10
* @param key 当前时间戳
* */
public static String postKey(String appid,String keyid,String key,String username){
return string2MD5(appid+keyid+key+username+"BDTTtaID");
}
/**
* 发布评论
* md5(_appid+commentid+_key+username+私钥),私钥:BDTTtaID
* @param appid 4
* @param keyid 内容索引ID 可以是栏目cid和内容id组合,例如:1-10
* @param key 当前时间戳
* */
public static String returnPostKey(String appid,String commentid,String key,String username){
return string2MD5(appid+commentid+key+username+"BDTTtaID");
}
/**
* 加密解密算法 执行一次加密,两次解密
*/
public static String convertMD5(String inStr){
char[] a = inStr.toCharArray();
for (int i = 0; i < a.length; i++){
a[i] = (char) (a[i] ^ 't');
}
String s = new String(a);
return s;
}
/*
* String s = new String("password");
* ("原始:" + s);
* ("MD5后:" + string2MD5(s));
* ("加密的:" + convertMD5(s));
* ("解密的:" + convertMD5(convertMD5(s)));
*/
}
防止卡顿scrollview类
public class MyScrollViewVideo extends ScrollView{
private GestureDetector mGestureDetector;
public MyScrollViewVideo(Context context, AttributeSet attrs) {
super(context, attrs);
//初始化手势
mGestureDetector = new GestureDetector(context, new YScrollDetector());
}
/**
* touch事件的拦截函数
* @param ev
* @return
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//根据手势决定是否拦截子控件的onTouch事件
return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
}
/**
* 控件的手势监听
*/
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
//当纵向滑动的距离大于横向滑动的距离的时候,返回true
if (Math.abs(distanceY) > Math.abs(distanceX)) {
return true;
}
return false;
}
}
}
网络工具类
public class NetUtils {
private NetUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 判断网络是否连接
*
* @param context
* @return
*/
public static boolean isConnected(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != connectivity) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (null != info && info.isConnected()) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
/**
* 判断是否是wifi连接
*/
public static boolean isWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return false;
return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
}
/**
* 打开网络设置界面
*/
public static void openSetting(Activity activity) {
Intent intent = new Intent("/");
ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
intent.setComponent(cm);
intent.setAction("android.intent.action.VIEW");
activity.startActivityForResult(intent, 0);
}
}
图片处理工具类
public class Options {
public final static int NEWS_RUNNABLE_CODE = 4001;
public static String CHANNLE_USER_DATA = "userData";
public static String CHANNLE_OTHER_DATA = "otherData";
public static String CHANNLE_BOTH_DATA = "bothData";
public static ImageLoaderConfiguration getImageConfig(Context context){
File cacheDir = StorageUtils.getOwnCacheDirectory(context, "ImageCache/Cache");
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
//.memoryCacheExtraOptions(480, 800) // default = device screen dimensions 内存缓存文件的最大长宽
.threadPoolSize(4) // default 线程池内加载的数量
.threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级
.tasksProcessingOrder(QueueProcessingType.FIFO) // default
.denyCacheImageMultipleSizesInMemory()
.discCache(new UnlimitedDiscCache(cacheDir))//自定义缓存路径
.memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现
.memoryCacheSize(2 * 1024 * 1024) // 内存缓存的最大值
.memoryCacheSizePercentage(13) // default
.discCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值
.discCacheFileCount(1000) // 可以缓存的文件数量
.imageDownloader(new BaseImageDownloader(context)) // default
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
.build(); //开始构建
return config;
}
public static DisplayImageOptions getImageOption(){
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.armheadlines_banner)
.showImageForEmptyUri(R.drawable.armheadlines_banner)
.showImageOnFail(R.drawable.armheadlines_banner)
.cacheInMemory(true)
.cacheOnDisc(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
return options;
}
public static DisplayImageOptions getSmallOption(){
DisplayImageOptions optionssmall = new DisplayImageOptions.Builder()
// 设置图片在下载期间显示的图片
.showImageOnLoading(R.drawable.armheadlines_publisher_photo)
// 设置图片Uri为空或是错误的时候显示的图片
.showImageForEmptyUri(R.drawable.armheadlines_publisher_photo)
// 设置图片加载/解码过程中错误时候显示的图片
.showImageOnFail(R.drawable.armheadlines_publisher_photo)
.cacheInMemory(true).cacheOnDisc(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
return optionssmall;
}
}
应用更新工具类
public class UpdateManager {
/* 下载中 */
private static final int DOWNLOAD = 1;
/* 下载结束 */
private static final int DOWNLOAD_FINISH = 2;
/* 下载保存路径 */
private String mSavePath;
/* 记录进度条数量 */
private int progress;
/* 是否取消更新 */
private boolean cancelUpdate = false;
private Context mContext;
/* 更新进度条 */
private ProgressBar mProgress;
private Dialog mDownloadDialog;
private SSOController ssoController;
private UpSoftBean softBean;
private Button btn_confirm;
private Button btn_cancel;
private String urlStr;
private boolean isShowToast;
private int result = -1;
private CheckListener checkListener;
public void setCheckListener(CheckListener checkListener) {
this.checkListener = checkListener;
}
public interface CheckListener {
void onFinished(int result);
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
// 正在下载
case DOWNLOAD:
// 设置进度条位置
mProgress.setProgress(progress);
mProgressPercent.setText(progress + "%");
break;
case DOWNLOAD_FINISH:
// 安装文件
// installApk();
openApk();
break;
default:
break;
}
};
};
private TextView mCancle;
private TextView mProgressPercent;
public UpdateManager(Context context, boolean isShowToast) {
this.mContext = context;
ssoController = new SSOController();
this.isShowToast = isShowToast;
}
/**
* 检查软件是否有更新版本
*
* @return
*/
public void checkUpdate() {
// 获取当前软件版本
String version = VersionUtils.getVersionName(mContext);
String josnString = "versionnum=" + version + "&yw_name=" + C.serverSoftName;
Log.v("dd", "update==========" + version + "----------json=======" + josnString);
installThread(josnString);
}
/**
* 显示软件更新对话框
*/
private void showNoticeDialog() {
// 构造对话框
LayoutInflater iLayoutInflater = LayoutInflater.from(mContext);
View view = (View) iLayoutInflater.inflate(R.layout.dialog_check_updata, null);
btn_confirm = (Button) view.findViewById(R.id.btn_confirm);
btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
final Dialog d = builder.setView(view).create();
btn_confirm.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
d.dismiss();
showDownloadDialog();
}
});
btn_cancel.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(d.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = 400;
d.getWindow().setAttributes(lp);
}
/**
* 显示软件下载对话框
*/
private void showDownloadDialog() {
// 构造软件下载对话框
// 构造软件下载对话框
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
// UserDialog.Builder builder = new UserDialog.Builder(mContext);
// builder.setTitle(R.string.soft_updating);
// 给下载对话框增加进度条
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.softupdate_progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
mProgressPercent = (TextView) v.findViewById(R.id.check_update_percent);
mCancle = (TextView) v.findViewById(R.id.check_update_cancel);
builder.setView(v);
// 取消更新
mCancle.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
cancelUpdate = true;
}
});
mDownloadDialog = builder.create();
mDownloadDialog.show();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(mDownloadDialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
mDownloadDialog.getWindow().setAttributes(lp);
// 现在文件
downloadApk();
}
/**
* 下载apk文件
*/
private void downloadApk() {
// 启动新线程下载软件
new downloadApkThread().start();
}
/**
* 下载文件线程
*
*/
private class downloadApkThread extends Thread {
@Override
public void run() {
try {
BufferedReader input = null;
StringBuilder sb = null;
HttpURLConnection con = null;
// 判断SD卡是否存在,并且是否具有读写权限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// 获得存储卡的路径
String sdpath = Environment.getExternalStorageDirectory() + "/";
mSavePath = sdpath + "download";
Log.d("yangxf", " download Apk Thread urlStr = " + urlStr);
URL url = new URL(urlStr);
// 创建连接
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
if (url.getProtocol().toLowerCase().equals("https")) {
https.setHostnameVerifier(DO_NOT_VERIFY);
con = https;
} else {
con = (HttpURLConnection) url.openConnection();
}
try {
input = new BufferedReader(new InputStreamReader(con.getInputStream()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int length = con.getContentLength();
Log.d("zhsy", "length = " + length);
InputStream is = con.getInputStream();
File file = new File(mSavePath);
// 判断文件目录是否存在
if (!file.exists()) {
file.mkdir();
}
File apkFile = new File(mSavePath, VersionUtils.getVersionName(mContext));
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
// 缓存
byte buf[] = new byte[1024];
// 写入到文件中
do {
int numread = is.read(buf);
count += numread;
// 计算进度条位置
progress = (int) (((float) count / length) * 100);
// 更新进度
mHandler.sendEmptyMessage(DOWNLOAD);
if (numread <= 0) {
// 下载完成
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
// 写入文件
fos.write(buf, 0, numread);
} while (!cancelUpdate);// 点击取消就停止下载.
fos.close();
is.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 取消下载对话框显示
mDownloadDialog.dismiss();
}
};
/**
* 安装APK文件
*/
private void installApk() {
File apkfile = new File(mSavePath, VersionUtils.getVersionName(mContext));
if (!apkfile.exists()) {
return;
}
// 通过Intent安装APK文件
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(i);
}
/**
* 安装完成时打开APK文件
*/
private void openApk() {
File apkfile = new File(mSavePath, VersionUtils.getVersionName(mContext));
if (!apkfile.exists()) {
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
}
public void installThread(final String josnString) {
new Thread(new Runnable() {
@Override
public void run() {
softBean = ssoController.doUpSoftHttpsPost(C.serverSoftUpdate, josnString);
handler.sendEmptyMessage(0);
}
}).start();
}
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@SuppressLint("NewApi")
public void handleMessage(Message message) {
switch (message.what) {
case 0:
if (softBean != null && softBean.update == 1 && softBean.rt == 0) {
result = 1;
urlStr = C.hpServerHead + softBean.result.apkurl;
Log.d("dd", "urlString=====" + urlStr);
showNoticeDialog();
} else {
result = -1;
if (isShowToast) {
Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
}
}
break;
default:
break;
}
}
};
/**
* Trust every server - dont check for any certificate
*/
private static void trustAllHosts() {
final String TAG = "trustAllHosts";
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
Log.i(TAG, "checkClientTrusted");
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
Log.i(TAG, "checkServerTrusted");
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
}
本地数据存储工具类
public class SPDataTools {
public static final String FILE="noClear";
public static void spClean(Context context) {
SharedPreferences.Editor editor = AppApplication.geContext()
.getSharedPreferences(Constants.SPFILE, Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
}
public static String spGetFirstTime(Context context) {
SharedPreferences preferences = context.getSharedPreferences(FILE, Context.MODE_PRIVATE);
return preferences.getString("isfirst_time", "");
}
/** 第一次有数据的时间 */
public static void spSaveIsFirstTime(Context context, String time) {
SharedPreferences.Editor editor = context.getSharedPreferences(FILE, Context.MODE_PRIVATE).edit();
editor.putString("isfirst_time", time);
editor.commit();
}
public static String spGetCID(Context context, String id, String cid) {
SharedPreferences preferences = context.getSharedPreferences(Constants.SPFILE, Context.MODE_PRIVATE);
return preferences.getString(id + "-" + cid, "");
}
public static void spSaveCID(Context context, String id, String cid, String json) {
SharedPreferences.Editor editor = context.getSharedPreferences(Constants.SPFILE, Context.MODE_PRIVATE).edit();
editor.putString(id + "-" + cid, json);
editor.commit();
}
public static String spGetSubscribCID(Context context, String id, String cid) {
SharedPreferences preferences = context.getSharedPreferences(Constants.SPFILE, Context.MODE_PRIVATE);
return preferences.getString(id + "," + cid, "");
}
public static void spSaveSubscribCID(Context context, String id, String cid, String json) {
SharedPreferences.Editor editor = context.getSharedPreferences(Constants.SPFILE, Context.MODE_PRIVATE).edit();
editor.putString(id + "," + cid, json);
editor.commit();
}
public static String spGetSubjectCID(Context context, String id, String cid) {
SharedPreferences preferences = context.getSharedPreferences(Constants.SPFILE, Context.MODE_PRIVATE);
return preferences.getString(id + "~" + cid, "");
}
public static void spSaveSubjectCID(Context context, String id, String cid, String json) {
SharedPreferences.Editor editor = context.getSharedPreferences(Constants.SPFILE, Context.MODE_PRIVATE).edit();
editor.putString(id + "~" + cid, json);
editor.commit();
}
}