常用自定义工具类

3 分钟 阅读

磁盘操作类

获取内存卡下某个存储路径

public static String getDirectoryPath(String dirName) {
	String root = Environment.getExternalStorageDirectory()
			.getAbsolutePath();
	String path = root + "/" + Constants.ROOT_DIR + "/" + dirName + "/";
	File dir = new File(path);
	if (!dir.exists()) {
		dir.mkdirs();
	}
	return path;
	}

Bitmap保存为本地文件

public static void write2File(Bitmap bitmap, String fileName) {
	File file = new File(fileName+".jpg");
	BufferedOutputStream out = null;
	try {
		out = new BufferedOutputStream(new FileOutputStream(file));
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
		if (out != null) {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

奔溃日志保存

public class CrashHandler implements UncaughtExceptionHandler {

    private Context mContext;
    private String toastMsg = "程序异常退出";
    private OnCrashHandler onCrashHandler;

    //系统默认的UncaughtException处理类
    private UncaughtExceptionHandler mDefaultHandler;
    //错误报告文件的扩展名
    private static final String CRASH_REPORTER_EXTENSION = ".log";

    private final String mPath = FileUtils.getDirectoryPath("crash");
    private final String TAG = CrashHandler.class.getSimpleName();
    // 用来存储设备信息和异常信息
    private Map<String, String> mInfos = new TreeMap<>();
    // 用于格式化日期,作为日志文件名的一部分
    private DateFormat mFormat = new SimpleDateFormat("yyyyMMdd-HHmmss",Locale.getDefault());

    private static class CrashHandlerInstance {
        private static final CrashHandler instance = new CrashHandler();
    }

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return CrashHandlerInstance.instance;
    }

    /**
     * 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器
     */
    public static void initCrashHandler(Context context) {
        initCrashHandler(context, null);
    }

    public static void initCrashHandler(Context context, String toastMsg) {
        initCrashHandler(context, toastMsg, null);
    }

    public static void initCrashHandler(Context context, String toastMsg,
                                        OnCrashHandler onCrashHandler) {
        CrashHandler crashHandler = getInstance();
        if (null != toastMsg) {
            crashHandler.toastMsg = toastMsg;
        }
        crashHandler.onCrashHandler = onCrashHandler;
        crashHandler.mContext = context;
        // 获取系统默认的UncaughtException处理器
        crashHandler.mDefaultHandler = Thread
                .getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(crashHandler);
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @SuppressWarnings("unused")
	@Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
        	if(false){//暂不使用
        		 SystemClock.sleep(3000);
                 Intent intent = new Intent(mContext.getApplicationContext(), null);
                 PendingIntent restartIntent = PendingIntent.getActivity(mContext.getApplicationContext(), 0, intent,
                         PendingIntent.FLAG_CANCEL_CURRENT);
                 //进程死亡时调用系统级调用系统级服务重新开启应用
                 AlarmManager manager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
                 manager.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
                 android.os.Process.killProcess(android.os.Process.myPid());
                 System.exit(0);
        	}
        	mDefaultHandler.uncaughtException(thread, ex);
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false
     */
    protected boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        if (onCrashHandler != null && onCrashHandler.onCrash(ex)) {
            return true;
        }
        // 使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                // Toast 显示需要出现在一个线程的消息队列中
                Looper.prepare();
                Toast.makeText(mContext, toastMsg, Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }.start();
        //收集设备参数信息;保存日志文件;
        // 收集设备参数信息
        collectDeviceInfo();
        // 保存日志文件
        saveCrashInfo2File(ex);
        return true;
    }

    /**
     * 收集设备参数信息
     */
    private void collectDeviceInfo() {
        try {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(),
                    PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null"
                        : pi.versionName;
                String versionCode = pi.versionCode + "";
                mInfos.put("VersionName", versionName);
                mInfos.put("VersionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Logger.e(TAG, "an error occured when collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                mInfos.put(field.getName(), field.get(null).toString());
                Logger.e(TAG, field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Logger.e(TAG, "an error occured when collect crash info", e);
            }
        }
    }

    /**
     * 保存日志文件
     */
    private String saveCrashInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        sb.append(TimeUtils.millisToStringDate(System
                .currentTimeMillis()) + System.getProperty("line.separator"));

        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);
        //设备信息
        for (Map.Entry<String, String> entry : mInfos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + System.getProperty("line.separator"));
        }
        Logger.e(TAG, result);

        OutputStream os = null;
        String fileName = mFormat.format(new Date()) + "-" + System.currentTimeMillis()
                + CRASH_REPORTER_EXTENSION;
        File file = new File(mPath + fileName);
        try {
            if (!file.exists() && !file.createNewFile()) {
                Logger.e(TAG, "CrashHandler处理文件创建失败");
                return null;
            }

            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                os = new FileOutputStream(file);
                os.write(sb.toString().getBytes());
                os.close();
            }
            return fileName;
        } catch (Exception e) {
            Logger.e(TAG, "an error occured while writing file...", e);
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public interface OnCrashHandler {
	 boolean onCrash(Throwable e);
    }
}

复制assets文件到指定目录

/**
     * 将sample工程需要的资源文件拷贝到SD卡中使用(授权文件为临时授权文件,请注册正式授权)
     *
     * @param isCover 是否覆盖已存在的目标文件
     * @param source
     * @param dest
     */
    private void copyFromAssetsToSdcard(boolean isCover, String source, String dest) {
        File file = new File(dest);
        if (isCover || (!isCover && !file.exists())) {
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = WApplication.getInstance().getAssets().open(source);
                String path = dest;
                fos = new FileOutputStream(path);
                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = is.read(buffer, 0, 1024)) >= 0) {
                    fos.write(buffer, 0, size);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }