- Md5Util
- LogUtils
- NetUtils
Md5Util
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* author Phyooos
* date 16/4/6.
*/
public class Md5Utils {
/**
*@param flag 是否32位加密
*@param str 传入数据
*@author Phyooos
*@data 16/4/6 22:56
*/
public static String encryptByMd5(String str,boolean flag) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(str.getBytes());
byte [] result = messageDigest.digest();
int j ;
StringBuffer stringBuffer = new StringBuffer("");
for(int offest = 0 ;offest<result.length;offest++){
j = result[offest];
if(j<0){j+=256;}
if(j>16){stringBuffer.append("");}
stringBuffer.append(Integer.toString(j));
}
return flag?stringBuffer.toString():stringBuffer.toString().substring(8,24);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
LogUtils
import android.util.Log;
/**
* Log统一管理类
*
* author Phyooos
* date 16/4/6.
*/
public class L{
private L(){
throw new UnsupportedOperationException("cannot be instantiated");
}
// 在application的onCreate函数里面初始化
public static boolean isDebug = true;
private static final String TAG = "Phyooos";
// 四个是默认tag的函数
public static void i(String msg){
if (isDebug)Log.i(TAG, msg);
}
public static void d(String msg){
if (isDebug)Log.d(TAG, msg);
}
public static void e(String msg){
if (isDebug)Log.e(TAG, msg);
}
public static void v(String msg){
if (isDebug)Log.v(TAG, msg);
}
// 自定义tag的函数
public static void i(String tag, String msg){
if (isDebug)Log.i(tag, msg);
}
public static void d(String tag, String msg){
if (isDebug)Log.i(tag, msg);
}
public static void e(String tag, String msg){
if (isDebug)Log.i(tag, msg);
}
public static void v(String tag, String msg){
if (isDebug)Log.i(tag, msg);
}
}
NetUtils
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* author Phyooos
* date 16/4/6.
*/
public class NetUtils {
private NetUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 判断网络是否连接
*
* @param context
* @return true 已打开 false 未打开
*/
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(final Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("网络设置").setMessage("网络连接不可用,是否设置?")
.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = null;
//判断手机系统的版本
if (android.os.Build.VERSION.SDK_INT > 10) {
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
} else {
intent = new Intent();
ComponentName component = new ComponentName("com.android.settings",
"com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
activity.startActivity(intent);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
SPUtils
package com.klgz.wskj.utils;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.klgz.wskj.global.GlobalApplication;
import com.klgz.wskj.modle.UserInfoMod;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
public class SPUtils {
private static Gson gson = new Gson();
public SPUtils()
{
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 保存在手机里面的文件名
*/
public static final String FILE_NAME = "share_data";
private Context context = GlobalApplication.getmContext();
/**
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
*
* @param context
* @param key
* @param object
*/
public static void put(Context context, String key, Object object)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (object instanceof String)
{
editor.putString(key, (String) object);
} else if (object instanceof Integer)
{
editor.putInt(key, (Integer) object);
} else if (object instanceof Boolean)
{
editor.putBoolean(key, (Boolean) object);
} else if (object instanceof Float)
{
editor.putFloat(key, (Float) object);
} else if (object instanceof Long)
{
editor.putLong(key, (Long) object);
} else
{
editor.putString(key, object.toString());
}
SharedPreferencesCompat.apply(editor);
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*
* @param context
* @param key
* @param defaultObject
* @return
*/
public static Object get(Context context, String key, Object defaultObject)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
if (defaultObject instanceof String)
{
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer)
{
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean)
{
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float)
{
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long)
{
return sp.getLong(key, (Long) defaultObject);
}
return null;
}
/**
* 移除某个key值已经对应的值
*
* @param context
* @param key
*/
public static void remove(Context context, String key)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
SharedPreferencesCompat.apply(editor);
}
/**
* 清除所有数据
*
* @param context
*/
public static void clear(Context context)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
SharedPreferencesCompat.apply(editor);
}
/**
* 查询某个key是否已经存在
*
* @param context
* @param key
* @return
*/
public static boolean contains(Context context, String key)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
return sp.contains(key);
}
/**
* 返回所有的键值对
*
* @param context
* @return
*/
public static Map<String, ?> getAll(Context context)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
return sp.getAll();
}
/**
* 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
*
* @author zhy
*
*/
private static class SharedPreferencesCompat
{
private static final Method sApplyMethod = findApplyMethod();
/**
* 反射查找apply的方法
*
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Method findApplyMethod()
{
try
{
Class clz = SharedPreferences.Editor.class;
return clz.getMethod("apply");
} catch (NoSuchMethodException e)
{
}
return null;
}
/**
* 如果找到则使用apply执行,否则使用commit
*
* @param editor
*/
public static void apply(SharedPreferences.Editor editor)
{
try
{
if (sApplyMethod != null)
{
sApplyMethod.invoke(editor);
return;
}
} catch (IllegalArgumentException e)
{
} catch (IllegalAccessException e)
{
} catch (InvocationTargetException e)
{
}
editor.commit();
}
}
/**
* 获取本地保存的用户信息
* @return
*/
public static UserInfoMod getUserInfo(Context context) {
UserInfoMod user = null;
String json = (String) get(context,"UserInfoMod",null);
try {
user = gson.fromJson(json, new TypeToken<UserInfoMod>(){}.getType());
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
/**
* 设置本地保存的用户信息
* @return
*/
public static void setUserInfo(Context context,UserInfoMod user) {
put(context,"UserInfoMod",gson.toJson(user));
}
/**
* 删除本地保存的用户信息
* @return
*/
public static void removeUserInfo(Context context,String key) {
remove(context,key);
}
}
TextUtils
import android.text.TextUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by yoko on 6/10/15.
*/
public class StringUtils
{
public static boolean isStringEmpty(String str)
{
return (str == null) || (str.length() == 0) || (str.trim().length() == 0);
}
public static boolean isBlank(String str)
{
int strLen = 0;
if ((str == null) || ((strLen = str.length()) == 0)) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
}
public static boolean equalsNull(String str)
{
return (isBlank(str)) || (str.equalsIgnoreCase("null"));
}
public static boolean isNumeric(String str)
{
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static String md5Helper(String plainText)
{
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte[] b = md.digest();
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++)
{
int i = b[offset];
if (i < 0) {
i += 256;
}
if (i < 16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
return buf.toString();
} catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e);
}
}
private static String getSubStr(String str, int subNu, String replace)
{
int strLength = str.length();
if (strLength >= subNu) {
str = str.substring(strLength - subNu, strLength);
} else {
for (int i = strLength; i < subNu; i++) {
str = str + replace;
}
}
return str;
}
public static String getUUIDString(String tBrand, String tSeries, String tUnique, int subNu,
String replace)
{
return md5Helper(getSubStr(tBrand, subNu, replace) +
getSubStr(tSeries, subNu, replace) +
getSubStr(tUnique, subNu, replace));
}
public static String encodeStr(String str)
{
if (TextUtils.isEmpty(str)) {
return "";
}
try
{
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return str;
}
public static boolean isDigit(String strNum)
{
Pattern pattern = Pattern.compile("[0-9]{1,}");
Matcher matcher = pattern.matcher(strNum);
return matcher.matches();
}
public static String stringChangeCapital(String s)
{
if (equalsNull(s)) {
return "";
}
char[] c = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
if ((c[i] >= 'a') && (c[i] <= 'z')) {
c[i] = Character.toUpperCase(c[i]);
} else if ((c[i] >= 'A') && (c[i] <= 'Z')) {
c[i] = Character.toLowerCase(c[i]);
}
}
return String.valueOf(c);
}
public static String addComma3(String str)
{
if (equalsNull(str)) {
return "";
}
str = new StringBuilder(str).reverse().toString();
String str2 = "";
for (int i = 0; i < str.length(); i++)
{
if (i * 3 + 3 > str.length())
{
str2 = str2 + str.substring(i * 3, str.length());
break;
}
str2 = str2 + str.substring(i * 3, i * 3 + 3) + ",";
}
if (str2.endsWith(",")) {
str2 = str2.substring(0, str2.length() - 1);
}
return new StringBuilder(str2).reverse().toString();
}
public static String handlerStr(String str, int length)
{
if ((str != null) && (!"".equals(str)))
{
if (str.length() > 15)
{
String s = str.substring(0, 15) + "...";
return s;
}
return str;
}
return "";
}
public static String getPlayCountsToStr(long playCount)
{
if (playCount < 10000L)
{
if (playCount < 1000L) {
return "" + playCount;
}
if ((playCount >= 1000L) && (playCount <= 9999L))
{
String aa = "" + playCount / 1000L;
String bb = "" + playCount % 1000L;
if (bb.length() < 3) {
bb = "0" + bb;
}
return aa + "," + bb;
}
return "";
}
if ((playCount >= 10000L) && (playCount < 100000000L))
{
DecimalFormat df = new DecimalFormat(".#");
String st = df.format(playCount * 1.0D / 10000.0D) + "Íò";
return st;
}
DecimalFormat df = new DecimalFormat(".#");
String st = df.format(playCount * 1.0D / 100000000.0D) + "ÒÚ";
return st;
}
}
FileUtils
mport java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.klgz.app.config.AppConstants;
public class FileUtils {
public static void saveBitmap(String directory,String fileName,Bitmap bitmap) {
File directoryFile = new File(directory);
if(!directoryFile.exists()){
directoryFile.mkdirs();
}
File f = new File(directoryFile, fileName);
if (f.exists()) {
f.delete();
}
try {
FileOutputStream out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Bitmap getBitmap(String fileName){
Bitmap bitmap = BitmapFactory.decodeFile(AppConstants.ROOT_PATH+fileName);
return bitmap;
}
}
DeviceUtils
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
/**
* 设备工具类
*
* @author LETV
*/
public class DeviceUtils {
public static final String LETV_MOBILE_DEVICE_X600 = "X600";
public static final String LETV_MOBILE_DEVICE_X601 = "X601";
public static final String LETV_MOBILE_DEVICE_X800 = "X800";
public static final String LETV_MOBILE_DEVICE_X900 = "X900";
/**
* 获取设备型号
*
* @return android.os.build.MODEL
*/
public static String getDeviceModel() {
return android.os.Build.MODEL;
}
/**
* 获取设备名称,在X600上获取到的是“X600”<br>
* 上面getDeviceModel获取到的是“android X600”
*
* @return android.os.build.DEVICE
*/
public static String getTerminalSeries() {
return android.os.Build.DEVICE;
}
/** 是否第三方设备 */
// 由于保密原因android.os.getString("ro.product.brand") ?= letv
// 没有设置正确的brand
// 目前根据model中是否含有三款机型的型号来判断是否乐视手机
// TODO:正式发布前修改逻辑。
public static boolean isOtherDevice() {
String model = android.os.Build.MODEL;
if (StringUtils.equalsNull(model)) {
return true;
}
if (model.contains(LETV_MOBILE_DEVICE_X600)
|| model.contains(LETV_MOBILE_DEVICE_X601)
|| model.contains(LETV_MOBILE_DEVICE_X900)) {
return false;
}
return true;
}
/**
* 获取设备ID,先取IMEI,获取不到取mac地址的MD5值作为设备id
*/
public static String getDeviceId(Context context) {
if (context == null) {
return "";
}
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
String deviceId = telephonyManager.getDeviceId();
if (deviceId != null && deviceId.length() > 0) {
return deviceId;
}
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo == null) {
throw new RuntimeException(
"getIEMI(Context context):wifiManager.getConnectionInfo() ==> null");
}
String macAddress = wifiInfo.getMacAddress();
if (macAddress == null || "".equals(macAddress.trim())) {
throw new RuntimeException(
"getIEMI(Context context):wifiInfo.getMacAddress() ==> null");
}
return MD5Util.MD5(macAddress);
}
}
时间: 2024-10-11 20:05:16