您的位置:首页 > 编程语言 > Java开发

Java常见工具类封装

2016-05-26 11:14 671 查看
MD5加密



import android.annotation.SuppressLint;
import java.security.MessageDigest;

public class MD5 {

@SuppressLint("DefaultLocale")
public static String hex(byte[] array) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
.toUpperCase().substring(1, 3));
}
return sb.toString();
}

public static String encrypt(String message) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
return hex(md.digest(message.getBytes("ISO8859-1")));
} catch (Exception e) {
}
return null;
}

public static void main(String[] args) {
System.out.println(encrypt("Hello world"));
}


SharedPreferences 的一个工具类,调用setParam 就能保存String, Integer, Boolean, Float, Long类型的参数 同样调用getParam就能获取到保存在手机里面的数据

SharedPreferences详细的介绍请参考之前的博客/article/4894468.html



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

/**
* SharedPreferences的一个工具类,调用setParam
* 就能保存String, Integer, Boolean, Float,
* Long类型的参数 同样调用getParam就能获取到保存在手机里面的数据
*
* 可以存储负责的对象
*
* @author Javen
*
*/
public class SPUtils {
/**
* 保存在手机里面的文件名
*/
private static final String FILE_NAME = "PSSDK";

/**
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
*
* @param context
* @param key
* @param object
*/
public static void setParam(Context context, String key, Object object) {

String type = object.getClass().getSimpleName();
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();

if ("String".equals(type)) {
editor.putString(key, (String) object);
} else if ("Integer".equals(type)) {
editor.putInt(key, (Integer) object);
} else if ("Boolean".equals(type)) {
editor.putBoolean(key, (Boolean) object);
} else if ("Float".equals(type)) {
editor.putFloat(key, (Float) object);
} else if ("Long".equals(type)) {
editor.putLong(key, (Long) object);
}

editor.commit();
}

/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*
* @param context
* @param key
* @param defaultObject
* @return
*/
public static Object getParam(Context context, String key,
Object defaultObject) {
String type = defaultObject.getClass().getSimpleName();
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);

if ("String".equals(type)) {
return sp.getString(key, (String) defaultObject);
} else if ("Integer".equals(type)) {
return sp.getInt(key, (Integer) defaultObject);
} else if ("Boolean".equals(type)) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if ("Float".equals(type)) {
return sp.getFloat(key, (Float) defaultObject);
} else if ("Long".equals(type)) {
return sp.getLong(key, (Long) defaultObject);
}

return null;
}
/**
* 获取复杂的对象
* @param context
* @param key
* @param defaultObject
* @return
*/
public static Object getObjectParam(Context context, String key,Object defaultObject){
String string=(String) getParam(context, key, defaultObject);
if (string!=null && !string.equals("")) {
return String2Object(string);
}
return null;
}
/**
* 设置负责的对象
* @param context
* @param key
* @param object
*/
public static void setObjectParam(Context context, String key,Object object){
setParam(context, key, Object2String(object));
}

/**
* 将Object转化为String
* @param object
* @return
*/
private static String Object2String(Object object) {

String string = null;
// 实例化一个ByteArrayOutputStream对象,用来装载压缩后的字节文件。
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = null;
try {

// 将得到的字符数据装载到ObjectOutputStream
os = new ObjectOutputStream(bos);
// writeObject 方法负责写入特定类的对象的状态,以便相应的 readObject 方法可以还原它
os.writeObject(object);
// 最后,用Base64.encode将字节文件转换成Base64编码保存在String中
string = new String(
Base64.encode(bos.toByteArray(), Base64.DEFAULT));

} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
return string;
}
/**
* 将String转化为Object
* @param string
* @return
*/
private static Object String2Object(String string) {
Object object = null;
byte[] mobileBytes = Base64.decode(string.getBytes(),
Base64.DEFAULT);
ByteArrayInputStream bis = new ByteArrayInputStream(mobileBytes);
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(bis);
object = ois.readObject();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (ois != null) {
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return object;
}

}


获取手机信息的工具类

需要添加权限

<uses-permission android:name="android.permission.READ_PHONE_STATE" />




import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
* 获取手机信息的工具类
* @author Javen
*
*/
public class PhoneHelper {

private static PhoneHelper mPhoneHelper;
private TelephonyManager tm;
private Context mContext;

private PhoneHelper (Context context){
mContext=context;
tm=(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
}

public static PhoneHelper getInstance(Context context){
if (mPhoneHelper==null) {
synchronized (PhoneHelper.class) {
if (mPhoneHelper==null) {
mPhoneHelper=new PhoneHelper(context);
}
}
}
return mPhoneHelper;
}
/**
* 获取手机型号
* @return
*/
public static String getModel() {
return android.os.Build.MODEL;
}

/**
* Firmware/OS 版本号
* @return
*/
public static String getVersionRelease() {
return android.os.Build.VERSION.RELEASE;
}

/**
* SDK版本号
* @return
*/
@SuppressWarnings("deprecation")
public static String getSdkApi() {
return android.os.Build.VERSION.SDK;
}

/**
* 获取手机屏幕分辨率
* @param activity
* @return
*/
public static String DisplayMetrics(Activity activity){
android.util.DisplayMetrics dm=new android.util.DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
//获得手机的宽度和高度像素单位为px
return "DisplayMetrics:" + dm.widthPixels+"* "+dm.heightPixels;
}

// 获取手机CPU信息
public static String getCpuInfo() {
String str1 = "/proc/cpuinfo";
String str2 = "";
String[] cpuInfo = { "", "" }; // 1-cpu型号 //2-cpu频率
String[] arrayOfString;
try {
FileReader fr = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
str2 = localBufferedReader.readLine();
arrayOfString = str2.split("\\s+");
for (int i = 2; i < arrayOfString.length; i++) {
cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
}
str2 = localBufferedReader.readLine();
arrayOfString = str2.split("\\s+");
cpuInfo[1] += arrayOfString[2];
localBufferedReader.close();
} catch (Exception e) {
}
return "1-cpu型号:" + cpuInfo[0] + "2-cpu频率:" + cpuInfo[1];
}

/**
* 去掉 +86|86 短信中心号和手机号码
*
* @param str
* @return
*/
public static String getSub(String str) {
String subStr = "";
try {
if (str == null) {
return "";
}
int len = str.length();
if (len > 11) {
subStr = str.substring(len - 11);
} else {
subStr = str;
}
} catch (Exception ioe) {

}
return subStr;
}

/**
* imei
* @return
*/
public String getImei(){
return tm.getDeviceId();
}
/**
* 获取手机号
* @return
*/
public String getPhone(){
return tm.getLine1Number();
}

/**
* IMSI 全称为 International Mobile Subscriber Identity,中文翻译为国际移动用户识别码。
* 它是在公众陆地移动电话网(PLMN)中用于唯一识别移动用户的一个号码。在GSM网络,这个号码通常被存放在SIM卡中
* @return
*/
public String getSubscriberId(){
if (isSimReady(mContext)) {
return tm.getSubscriberId();
}
return "";
}

/**
* 判断SIM卡是否准备好
*
* @param context
* @return
*/
public  boolean isSimReady(Context context) {
try {

int simState = tm.getSimState();
if (simState == TelephonyManager.SIM_STATE_READY) {
return true;
}
} catch (Exception e) {
Log.w("PhoneHelper", "021:" + e.toString());
}
return false;
}

/**
* 获取当前网络状况
*
* @return 如果网络已经连接,并且可用返回true, 否则false
* */
public static boolean getNetworkState(Context context) {
try {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo networkinfo = connectivity.getActiveNetworkInfo();
if (networkinfo != null) {
if (networkinfo.isAvailable() && networkinfo.isConnected()) {
return true;
}
}
}
} catch (Exception e) {
return false;
}
return false;
}

/**
* 判断是否模拟器。如果返回TRUE, 则当前是模拟器,模拟器IMEI是:00000000000000 运营商不让支付
*
* @param context
* @return
*
*/
public  boolean isEmulator(Context context) {
try {
String imei = tm.getDeviceId();
if (imei != null && imei.equals("000000000000000")) {
return true;
}
return (Build.MODEL.equals("sdk"))
|| (Build.MODEL.equals("google_sdk"));
} catch (Exception ioe) {
Log.w("PhoneHelper", "009:" + ioe.toString());
}
return false;
}

/**
* 获取当前APP名称和版本号
* @param context
* @return
* @throws Exception
*/
public static String getAppInfo(Context context) {
context=context.getApplicationContext();
String applicationName ="";
String versionName="";
String packageName ="";
int versionCode;
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
ApplicationInfo applicationInfo =packageManager.getApplicationInfo(context.getPackageName(), 0);

applicationName =  (String) packageManager.getApplicationLabel(applicationInfo);
versionName= packageInfo.versionName;
packageName= packageInfo.packageName;
versionCode = packageInfo.versionCode;
return  "applicationName:"+applicationName+ " packageName:"+packageName+" versionName:"+versionName+"  versionCode:"+versionCode;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

/**
* 获取当前APP名称和版本号
*
* @param context
* @return applicationName  packageName versionName versionCode
*/
public static Map<String, String> getAppInfoMap(Context context) {
String applicationName = "";
String versionName = "";
String packageName = "";
int versionCode;
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
ApplicationInfo applicationInfo = packageManager
.getApplicationInfo(context.getPackageName(), 0);

applicationName = (String) packageManager
.getApplicationLabel(applicationInfo);
versionName = packageInfo.versionName;
packageName = packageInfo.packageName;
versionCode = packageInfo.versionCode;
Map<String, String> map = new HashMap<String, String>();
map.put("appName", applicationName);
map.put("packageName", packageName);
map.put("versionName", versionName);
map.put("versionCode", versionCode + "");
return map;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}

/**
* 获取MetaDataValue
* @param name
* @param def
* @return
*/
public String getMetaDataValue(String name, String def) {
String value = getMetaDataValue(name);
return (value == null) ? def : value;
}
private String getMetaDataValue(String name) {
Object value = null;
PackageManager packageManager = mContext.getPackageManager();
ApplicationInfo applicationInfo;
try {
applicationInfo = packageManager.getApplicationInfo(mContext.getPackageName(),PackageManager.GET_META_DATA);
if (applicationInfo != null && applicationInfo.metaData != null) {
value = applicationInfo.metaData.get(name);
}
} catch (Exception e) {
}
return value.toString();
}
}


Log 工具类 可以保存日志到文件

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />



Log

反向代理获取Res

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
/**
* @author Javen
* 反向代理获取资源文件
*/
public final class Res {

/**  */
private Res() {

}

/** key for id */
private static final String ID = "id";
/** key for string */
private static final String STRING = "string";
/** key for layout */
private static final String LAYOUT = "layout";
/** key for style */
private static final String STYLE = "style";
/** key for drawable */
private static final String DRAWABLE = "drawable";
/** key for color */
private static final String COLOR = "color";
/** key for anim */
private static final String ANIM = "anim";
/** key for array */
private static final String ARRAY = "array";
/** key for attr */
private static final String ATTR = "attr";
/** key for dimen */
private static final String DIMEN = "dimen";
/** key for xml */
private static final String XML = "xml";

/**
* @param context
* @param name
*            res name
* @return res id
*/
public static int id(Context context, String name) {
return getIdentifier(context, ID, name);
}

/**
*
* @param context
* @param name
*            res name
* @return res id
*/
public static int string(Context context, String name) {
return getIdentifier(context, STRING, name);
}

/**
*
* @param context
* @param name
*            res name
* @return res id
*/
public static int layout(Context context, String name) {
return getIdentifier(context, LAYOUT, name);
}

/**
*
* @param context
* @param name
*            res name
* @return res id
*/
public static int style(Context context, String name) {
return getIdentifier(context, STYLE, name);
}

/**
*
* @param context
* @param name
*            res name
* @return res id
*/
public static int drawable(Context context, String name) {
return getIdentifier(context, DRAWABLE, name);
}

/**
*
* @param context
* @param name
*            res name
* @return res id
*/
public static int color(Context context, String name) {
return getIdentifier(context, COLOR, name);
}

/**
*
* @param context
* @param name
*            res name
* @return res id
*/
public static int anim(Context context, String name) {
return getIdentifier(context, ANIM, name);
}

/**
*
* @param context
* @param name
*            res name
* @return res id
*/
public static int array(Context context, String name) {
return getIdentifier(context, ARRAY, name);
}

/**
*
* @param context
* @param name
*            res name
* @return res id
*/
public static int attr(Context context, String name) {
return getIdentifier(context, ATTR, name);
}

/**
*
* @param context
* @param name
*            res name
* @return res id
*/
public static int dimen(Context context, String name) {
return getIdentifier(context, DIMEN, name);
}

/**
*
* @param context
* @param name
*            res name
* @return res id
*/
public static int xml(Context context, String name) {
return getIdentifier(context, XML, name);
}

/**
*
* @param context
* @param name
*            res name
* @return res
*/
public static String getString(Context context, String name) {
return context.getResources().getString(string(context, name));
}

public static String getString(String value, Object... obj) {
try {

if (obj != null && obj.length > 0) {
String flat = null;
int i = 1;
int maxLength = obj.length;
while(value.matches("(\n|.)*%\\d\\$s(\n|.)*") && i <= maxLength) {
flat = "%"+ i +"\\$s";
Object item = obj[i - 1];
value = value.replaceFirst(flat, item.toString());
i++;
}
}
return value;
} catch (Exception localException) {

}
return "";
}

/**
*
* @param context
* @param name
*            res name
* @return res
*/
public static int getColor(Context context, String name) {
return context.getResources().getColor(color(context, name));
}

/**
*
* @param context
* @param name
*            res name
* @return res
*/
public static Drawable getDrawable(Context context, String name) {
return context.getResources().getDrawable(drawable(context, name));
}

/**
*
* @param context
* @param name
*            res name
* @return res
*/
public static String[] getStringArray(Context context, String name) {
return context.getResources().getStringArray(array(context, name));
}

/**
*
* @param context
* @param name
*            res name
* @return res
*/
public static float getDimension(Context context, String name) {
return context.getResources().getDimension(dimen(context, name));
}

/**
*
* @param context
* @param name
*            res name
* @return res
*/
public static Animation getAnimation(Context context, String name) {
return AnimationUtils.loadAnimation(context, anim(context, name));
}

/**
*
* @param context
* @param type
*            res type
* @param attrName
*            res name
* @return res id
*/
private static int getIdentifier(Context context, String type, String attrName) {

if (context == null) {
throw new NullPointerException("the context is null");
}

if (type == null || type.trim().length() == 0) {
throw new NullPointerException("the type is null or empty");
}

if (attrName == null || attrName.trim().length() == 0) {
throw new NullPointerException("the attrNme is null or empty");
}

Resources res = context.getResources();
return res.getIdentifier(attrName, type, context.getApplicationContext().getPackageName());
}
}


Toast统一管理类



package com.javen.bs.pushsdk.utils;

import android.content.Context;
import android.widget.Toast;

/**
* Toast统一管理类
*/
public class T {
// Toast
private static Toast toast;

/**
* 短时间显示Toast
*
* @param context
* @param message
*/
public static void showShort(Context context, CharSequence message) {
if (null == toast) {
toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
// toast.setGravity(Gravity.CENTER, 0, 0);
} else {
toast.setText(message);
}
toast.show();
}

/**
* 短时间显示Toast
*
* @param context
* @param message
*/
public static void showShort(Context context, int message) {
if (null == toast) {
toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
// toast.setGravity(Gravity.CENTER, 0, 0);
} else {
toast.setText(message);
}
toast.show();
}

/**
* 长时间显示Toast
*
* @param context
* @param message
*/
public static void showLong(Context context, CharSequence message) {
if (null == toast) {
toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 0, 0);
} else {
toast.setText(message);
}
toast.show();
}

/**
* 长时间显示Toast
*
* @param context
* @param message
*/
public static void showLong(Context context, int message) {
if (null == toast) {
toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 0, 0);
} else {
toast.setText(message);
}
toast.show();
}

/**
* 自定义显示Toast时间
*
* @param context
* @param message
* @param duration
*/
public static void show(Context context, CharSequence message, int duration) {
if (null == toast) {
toast = Toast.makeText(context, message, duration);
// toast.setGravity(Gravity.CENTER, 0, 0);
} else {
toast.setText(message);
}
toast.show();
}

/**
* 自定义显示Toast时间
*
* @param context
* @param message
* @param duration
*/
public static void show(Context context, int message, int duration) {
if (null == toast) {
toast = Toast.makeText(context, message, duration);
// toast.setGravity(Gravity.CENTER, 0, 0);
} else {
toast.setText(message);
}
toast.show();
}

/** Hide the toast, if any. */
public static void hideToast() {
if (null != toast) {
toast.cancel();
}
}
}


对话框



import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

public class UI {

public interface ItemOnListener{
void itemOnListener(View view);
void closeOnListener(View view);
}

public static void showDialog(Context context,Bitmap bm,ItemOnListener listener){
//必须使用getApplicationContext() 否则不能再home显示对话框
showDialog(context.getApplicationContext(), Res.layout(context, "bs_image_layout"), Res.style(context, "bs_transparent_dialog"),bm, listener);
}

public static void showDialog(Context context,int resource,int style,Bitmap bm,final ItemOnListener listener){
View view=LayoutInflater.from(context).inflate(resource, null);
final AlertDialog dialog = new AlertDialog.Builder(context,style).create();
int sdkApi=Integer.parseInt(PhoneHelper.getSdkApi());
if (sdkApi>=19) {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
}
dialog.show();

WindowManager.LayoutParams params = dialog.getWindow().getAttributes();// 得到属性
params.gravity = Gravity.CENTER;// 显示在中间

DisplayMetrics metrics=  context.getResources().getDisplayMetrics();

int dispayWidth =metrics.widthPixels;
int dispayHeight =metrics.heightPixels;

params.width=(int)(dispayWidth * 0.8);
params.height=(int)(dispayHeight* 0.5);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);

dialog.getWindow().setAttributes(params);// 設置屬性
dialog.getWindow().setContentView(view);// 把自定義view加上去

Button closeButton = (Button) view.findViewById(Res.id(context, "bs_id_image_close"));
ImageView imageView = (ImageView) view.findViewById(Res.id(context, "bs_id_image"));
imageView.setImageBitmap(bm);
view.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
listener.itemOnListener(v);
dialog.dismiss();
}
});
closeButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
listener.closeOnListener(v);
dialog.dismiss();
}
});
}

/**
* dip 转换成px
*
* @param context
* @param dipValue
* @return
*/
public static int dip2px(Context context, float dipValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}

public static float getDensity(Context context) {
float density = context.getResources().getDisplayMetrics().density;
return density;
}

}


获取 AndroidManifest.xml 中meta-data值



import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
/**
* AndroidManifest.xml中的数据
* @author Javen
*
*/
public class MdUtil {
public static final String APPID = "AppId";
public static final String APPKEY = "AppKey";

public static String getMetadataApplicationId(Context context,String metaName) {
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
context.getPackageName(), PackageManager.GET_META_DATA);
if (ai.metaData != null) {
return ai.metaData.getString(metaName);
}
} catch (PackageManager.NameNotFoundException e) {
// if we can't find it in the manifest, just return null
}

return null;
}

public static void getAppIdOrAppkey(Context context){
if (Parameter.appId==null || Parameter.appId.equals("")) {
Parameter.appId=getMetadataApplicationId(context, APPID);
}
if (Parameter.appKey==null || Parameter.appKey.equals("")) {
Parameter.appKey=getMetadataApplicationId(context, APPKEY);
}
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: