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")); } MD5
SharedPreferences 的一个工具类,调用setParam 就能保存String, Integer, Boolean, Float, Long类型的参数 同样调用getParam就能获取到保存在手机里面的数据
SharedPreferences详细的介绍请参考之前的博客http://www.cnblogs.com/zyw-205520/archive/2013/04/09/3010912.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; } } SharedPreferences
获取手机信息的工具类
需要添加权限
<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(); } } PhoneHelperLog 工具类 可以保存日志到文件
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import android.os.Environment; import android.util.Log; /** * 带日志文件输入的,又可控开关的日志调试 */ public class L { public static Boolean isDebug=true; // 日志文件总开关 public static Boolean MYLOG_WRITE_TO_FILE=true;// 日志写入文件开关 private static char MYLOG_TYPE='v';// 输入日志类型,w代表只输出告警信息等,v代表输出所有信息 public static String MYLOG_PATH_SDCARD_DIR=Parameter.SD_PATH + "/error_log/";// 日志文件在sdcard中的路径 private static int SDCARD_LOG_FILE_SAVE_DAYS = 3;// sd卡中日志文件的最多保存天数 public static String MYLOGFILENAME = "Push_Log.txt";// 本类输出的日志文件名称 private static SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 日志的输出格式 public static SimpleDateFormat logfile = new SimpleDateFormat("yyyy-MM-dd");// 日志文件格式 public static final String TAG="Javen"; public static void w(String tag, Object msg) { // 警告信息 log(tag, msg.toString(), 'w'); } public static void e(String tag, Object msg) { // 错误信息 log(tag, msg.toString(), 'e'); } public static void d(String tag, Object msg) {// 调试信息 log(tag, msg.toString(), 'd'); } public static void i(String tag, Object msg) {// log(tag, msg.toString(), 'i'); } public static void v(String tag, Object msg) { log(tag, msg.toString(), 'v'); } public static void w(String tag, String text) { log(tag, text, 'w'); } public static void e(String tag, String text) { log(tag, text, 'e'); } public static void d(String tag, String text) { log(tag, text, 'd'); } public static void i(String tag, String text) { log(tag, text, 'i'); } public static void v(String tag, String text) { log(tag, text, 'v'); } /** * 根据tag, msg和等级,输出日志 * * @param tag * @param msg * @param level * @return void * @since v 1.0 */ public static void log(String tag, String msg, char level) { if (isDebug) { if ('e' == level && ('e' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { // 输出错误信息 Log.e(tag, msg); } else if ('w' == level && ('w' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { Log.w(tag, msg); } else if ('d' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { Log.d(tag, msg); } else if ('i' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { Log.i(tag, msg); } else { Log.v(tag, msg); } if (MYLOG_WRITE_TO_FILE){ writeLogtoFile(String.valueOf(level), tag, msg); delFile(); } } } /** * 打开日志文件并写入日志 * * @return * **/ private static void writeLogtoFile(String mylogtype, String tag, String text) {// 新建或打开日志文件 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ Date nowtime = new Date(); logfile.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); String needWriteFiel = logfile.format(nowtime); myLogSdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); String needWriteMessage = myLogSdf.format(nowtime) + " " + mylogtype + " " + tag + " " + text; File dir = new File(MYLOG_PATH_SDCARD_DIR); if (!dir.exists()) { dir.mkdirs(); } File file = new File(MYLOG_PATH_SDCARD_DIR, needWriteFiel + MYLOGFILENAME); try { FileWriter filerWriter = new FileWriter(file, true);//后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖 BufferedWriter bufWriter = new BufferedWriter(filerWriter); bufWriter.write(needWriteMessage); bufWriter.newLine(); bufWriter.close(); filerWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { L.log("tag", "SDK 无法使用", 'e'); } } /** * 删除制定的日志文件 * @throws ParseException * */ public static void delFile() {// 删除日志文件 BSPay_Log.txt /*String needDelFiel = logfile.format(getDateBefore()); File file = new File(MYLOG_PATH_SDCARD_DIR, needDelFiel + MYLOGFILEName); if (file.exists()) { file.delete(); }*/ try { File file = new File(MYLOG_PATH_SDCARD_DIR); File[] files = file.listFiles(); if (files != null) { for (File f1 : files) { String fileName=f1.getName(); if (fileName.contains(MYLOGFILENAME)) { String needDelFiel=fileName.substring(0,fileName.indexOf(MYLOGFILENAME)); logfile.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); Date fileDate=logfile.parse(needDelFiel); //比较时间date.before() boolean flag = getDateBefore().before(fileDate); if (!flag) { File logFile = new File(MYLOG_PATH_SDCARD_DIR, needDelFiel + MYLOGFILENAME); if (logFile.exists()) { logFile.delete(); } } } } } } catch (ParseException e) { e.printStackTrace(); } } /** * 得到现在时间前的几天日期,用来得到需要删除的日志文件名 * */ private static Date getDateBefore() { Date nowtime = new Date(); Calendar now = Calendar.getInstance(); now.setTime(nowtime); now.set(Calendar.DATE, now.get(Calendar.DATE) - SDCARD_LOG_FILE_SAVE_DAYS); return now.getTime(); } } Log
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(); } } } Toast对话框
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; } } showDialog
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); } } }Volley 二次封装工具类
import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import android.content.Context; import android.graphics.Bitmap; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request.Priority; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.ImageLoader.ImageContainer; import com.android.volley.toolbox.ImageLoader.ImageListener; import com.android.volley.toolbox.JsonObjectRequest; /** * 网络请求工具类 * @author Javen */ public class VolleyUtils { public interface volleyListener{ void onResponse(JSONObject response); void onErrorResponse(String message); } /** * * @param context * @param url * @param params * 用来保存post参数 */ public static void doPost(Context context, String url,HashMap<String, Object> params,final volleyListener listener) { // 优先级有LOW,NORMAL,HIGH,IMMEDIATE // 设置请求的优先级别通过覆写getPrioriity()方法 final Priority priority = Priority.HIGH; JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject( params), new Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // 正确响应时回调此函数 listener.onResponse(response); } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub listener.onErrorResponse(error.getMessage()); } }) { // 设置请求级别 @Override public Priority getPriority() { return priority; } // 设置请求头 @Override public Map<String, String> getHeaders() throws AuthFailureError { // TODO Auto-generated method stub return super.getHeaders(); } }; // 第一个代表超时时间:即超过30S认为超时,第三个参数代表最大重试次数,这里设置为1.0f代表如果超时,则不重试 req.setRetryPolicy(new DefaultRetryPolicy(1000*30, 1, 1.0f)); // 可以通过setTag方法为每一个Request添加tag req.setTag("My Tag"); // 也可以在我们实现的添加进RequestQueue的时候设置 VolleyController.getInstance(context).addToRequestQueue(req, "My Tag"); // 取消Request // VolleyController.getInstance(context).getRequestQueue().cancelAll("My Tag"); // 或者我们前面实现的方法 // VolleyController.getInstance(context).cancelPendingRequests("My Tag"); } public interface MyImageListener{ void setImageBitmap(Bitmap bitmap); } public static void loadImage(Context context,String url,final MyImageListener listener){ ImageLoader imageLoader=VolleyController.getInstance(context).getImageLoader(); imageLoader.get(url,new ImageListener(){ @Override public void onResponse(ImageContainer response,boolean arg) { if(response.getBitmap()!=null){ //设置imageView // imageView.setImageBitmap(response.getBitmap()); listener.setImageBitmap(response.getBitmap()); } } @Override public void onErrorResponse(VolleyError error){ throw new IllegalArgumentException("Image Error"+error.getMessage()); } }); } } VolleyUtils异常处理工具类
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.Thread.UncaughtExceptionHandler; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import java.util.TreeSet; import com.javen.bs.pushsdk.service.PushService; import android.content.Context; import android.os.Looper; import android.util.Log; /** * * @particulars:UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序,并记录发送错误报告.只是处理主线程的异常,要处理其他的异常的话, * 自己在起异常的时候调用 */ public class CrashHandler implements UncaughtExceptionHandler { public static final String TAG = "CrashHandler"; // 系统默认的UncaughtException处理类 private Thread.UncaughtExceptionHandler mDefaultHandler; // CrashHandler实例 private static CrashHandler INSTANCE = new CrashHandler(); // 程序的Context对象 private Context mContext; // 用来存储设备信息和异常信息 private Map<String, String> infos = new HashMap<String, String>(); // 用于格式化日期,作为日志文件名的一部分 private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); private static String LOGFILEName = "error_Log.txt";// 本类输出的日志文件名称 private static String LOG_PATH_SDCARD_DIR = Parameter.SD_PATH + "/error_log/";// 日志文件在sdcard中的路径 private boolean isSendStatus = false; /** 保证只有一个CrashHandler实例 */ private CrashHandler() { } /** 获取CrashHandler实例 ,单例模式 */ public static CrashHandler getInstance() { return INSTANCE; } /** * 初始化 * * @param context */ public void init(Context context) { mContext = context; // 获取系统默认的UncaughtException处理器 mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); // 设置该CrashHandler为程序的默认处理器 Thread.setDefaultUncaughtExceptionHandler(this); } /** * 当UncaughtException发生时会转入该函数来处理 */ public void uncaughtException(Thread thread, Throwable ex) { if (!handleException(ex) && mDefaultHandler != null) { // 如果用户没有处理则让系统默认的异常处理器来处理 mDefaultHandler.uncaughtException(thread, ex); } else { try { Thread.sleep(3000);// 如果处理了,让程序继续运行3秒再退出,保证文件保存并上传到服务器 } catch (InterruptedException e) { Log.e(TAG, "error : ", e); } // 退出程序 // android.os.Process.killProcess(android.os.Process.myPid()); // System.exit(1); } } /** * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. * * @param ex * @return true:如果处理了该异常信息;否则返回false. */ private boolean handleException(Throwable ex) { if (ex == null) { return false; } // 使用Toast来显示异常信息 new Thread() { @Override public void run() { Looper.prepare(); // Toast.makeText(mContext," I\'m sorry, abnormal program. ", Toast.LENGTH_LONG).show(); Looper.loop(); } }.start(); // 收集设备参数信息 collectDeviceInfo(mContext); // 保存错误报告文件 saveCrashInfo2File(ex); // 发送错误报告到服务器 sendCrashReportsToServer(mContext); return true; } /** * 收集设备参数信息 * * @param ctx */ public void collectDeviceInfo(Context ctx) { try { infos.put("phoneModel", PhoneHelper.getModel()); infos.put("SDKVersion", PhoneHelper.getSdkApi()); infos.put("getAppInfo", PhoneHelper.getAppInfo(ctx)); } catch (Exception e) { Log.e(TAG, "an error occured when collect package info", e); } } /** * 保存错误信息到文件中 * * @param ex * @return 返回文件名称,便于将文件传送到服务器 */ private String saveCrashInfo2File(Throwable ex) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : infos.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); sb.append(key + "=" + value + "\n"); } Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); ex.printStackTrace(printWriter); Throwable cause = ex.getCause(); while (cause != null) { cause.printStackTrace(printWriter); cause = cause.getCause(); } printWriter.close(); String result = writer.toString(); sb.append(result); try { formatter.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); String needWriteFiel = formatter.format(new Date()); File dir = new File(LOG_PATH_SDCARD_DIR); if (!dir.exists()) { dir.mkdirs(); } String fileName = needWriteFiel + LOGFILEName; File file = new File(LOG_PATH_SDCARD_DIR, fileName); FileWriter filerWriter = new FileWriter(file, true);// 后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖 BufferedWriter bufWriter = new BufferedWriter(filerWriter); bufWriter.write(sb.toString()); bufWriter.newLine(); bufWriter.close(); filerWriter.close(); return fileName; } catch (Exception e) { Log.e(TAG, "an error occured while writing file...", e); } return null; } // ///////////////////////////////////////////////////////////////////// /** * 把错误报告发送给服务器,包含新产生的和以前没发送的. * * @param ctx */ private void sendCrashReportsToServer(Context ctx) { String[] crFiles = getCrashReportFiles(ctx); if (crFiles != null && crFiles.length > 0) { TreeSet<String> sortedFiles = new TreeSet<String>(); sortedFiles.addAll(Arrays.asList(crFiles)); for (String fileName : sortedFiles) { // File cr = new File(ctx.getFilesDir(), fileName); final File cr = new File(LOG_PATH_SDCARD_DIR, fileName); //boolean sendStaus = postReport(cr); // 发送错误报告到服务器 String text =ReadTxtFile(cr.getAbsolutePath()); xxxx.sendLog(mContext, Parameter.URL_SEND_LOG, text, new PushService.pushListener() { @Override public void sendStatus(boolean isSuccess) { if (isSuccess) { cr.delete();// 删除已发送的报告 // cr.renameTo(new File(fileName)); } } }); } } } /** * 获取错误报告文件名 * * @param ctx * @return */ private String[] getCrashReportFiles(Context ctx) { // File filesDir = ctx.getFilesDir(); File filesDir = new File(LOG_PATH_SDCARD_DIR); // 实现FilenameFilter接口的类实例可用于过滤器文件名 FilenameFilter filter = new FilenameFilter() { // accept(File dir, String name) // 测试指定文件是否应该包含在某一文件列表中。 public boolean accept(File dir, String name) { return name.endsWith(".txt"); } }; // list(FilenameFilter filter) // 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中满足指定过滤器的文件和目录 return filesDir.list(filter); } // TODO 使用HTTP Post 发送错误报告到服务器 private boolean postReport(File file) { //String text =ReadTxtFile(file.getAbsolutePath()); return isSendStatus; } /** * 在程序启动时候, 可以调用该函数来发送以前没有发送的报告 */ public void sendPreviousReportsToServer() { sendCrashReportsToServer(mContext); } /** * 读取文本文件中的内容 * @param strFilePath * @return */ public static String ReadTxtFile(String strFilePath){ String path = strFilePath; String content = ""; //文件内容字符串 //打开文件 File file = new File(path); //如果path是传递过来的参数,可以做一个非目录的判断 if (file.isDirectory()){ Log.d("TestFile", "The File doesn't not exist."); } else{ try { InputStream instream = new FileInputStream(file); if (instream != null){ InputStreamReader inputreader = new InputStreamReader(instream); BufferedReader buffreader = new BufferedReader(inputreader); String line; //分行读取 while (( line = buffreader.readLine()) != null) { content += line + "\n"; } instream.close(); } } catch (java.io.FileNotFoundException e){ Log.d("TestFile", "The File doesn't not exist."); } catch (IOException e){ Log.d("TestFile", e.getMessage()); } } return content; } } CrashHandler