Android 2.3提供一个称为严苛模式(StrictMode)的调试特性,它将报告与线程及虚拟机相关的策略违例。StrictMode提供了各种的策略,这些策略能随时检查和报告开发者开发应用中存在的问题。
StrictMode的策略和规则
目前,有两大类的策略可供使用,一类是关于线程监控方面的,另外一类是关于VM虚拟机等方面的策略。
常用的线程监控方面的策略有:
Disk Reads 磁盘读
Disk Writes 磁盘写
Network access 网络访问
Custom Slow Code 自定义的运行速度慢的代码分析
常用的VM虚拟机策略有:
内存泄露的Activity对象
内存泄露的SQLite对象
内存泄露的释放的对象
使用示例:
import android.os.StrictMode;
@Override
protected void onCreate(Bundle savedInstanceState) {
openStrictMode();
...
}
...
private void openStrictMode() {
// 仅在调试模式设置严苛模式(StrictMode)
if (HYConfig.DEBUG) {
// 检测与线程相关的策略违例
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()// 检测所有策略
.permitDiskReads()// 屏蔽磁盘读策略
.permitDiskWrites()// 屏蔽磁盘写策略
.permitNetwork()// 屏蔽网络访问策略
.penaltyLog()// 表示将警告输出到LogCat
.penaltyDeath()// 一旦StrictMode消息被写到LogCat后应用就会崩溃
.build());
// 检测与虚拟机相关的策略违例
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
}
}
public static void displayBriefMemory(String name, Context context) {
final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(info);
MyLog.d("MyLog","=========内存检查: name="+name);
MyLog.d("MyLog","=========系统剩余内存:"+(info.availMem));
MyLog.d("MyLog", "=========系统是否处于低内存运行:" + info.lowMemory);
MyLog.d("MyLog","=========当系统剩余内存低于"+info.threshold+"时就看成低内存运行");
}
package cn.toltech.treefrog.util;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/** * 描述:自定义日志打印类 * 可控开关的日志调试,并可以输出到文件 * Created by huangyk on 2016/1/14. */
public class LogUtils {
private static String TAG = "LogUtils";
// 日志输出级别E
public static final int LEVEL_ERROR = 1;
// 日志输出级别W
public static final int LEVEL_WARN = 2;
// 日志输出级别I
public static final int LEVEL_INFO = 3;
// 日志输出级别D
public static final int LEVEL_DEBUG = 4;
// 日志输出级别V
public static final int LEVEL_VERBOSE = 5;
// 日志文件总开关
private static Boolean MYLOG_SWITCH = true;
// 日志写入文件开关
private static Boolean MYLOG_WRITE_TO_FILE = true;
// 输入日志类型
private static char MYLOG_LEVEL = 4;
// 日志文件存放目录
private static String MYLOG_PATH = "";
// sd卡中日志文件的最多保存天数
private static int MYLOG_FILE_SAVE_DAYS = 7;
// 本类输出的日志文件名称
private static String MYLOG_FILE_NAME = "run0219";
// 日志的输出格式
private static SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 日志文件的输出格式
private static SimpleDateFormat logfileSdf = new SimpleDateFormat("yyyy-MM-dd");
private LogUtils() {
}
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');
}
public static void e(String tag, Throwable tr) {
log(tag, Log.getStackTraceString(tr), 'e');
}
/** * 根据tag, msg和等级,输出日志 * * @return void * @since v 1.0 */
private static void log(String tag, String msg, char level) {
if (MYLOG_SWITCH) {
if ('e' == level && MYLOG_LEVEL >= LEVEL_ERROR) {
Log.e(tag, msg);
} else if ('w' == level && MYLOG_LEVEL >= LEVEL_WARN) {
Log.w(tag, msg);
} else if ('d' == level && MYLOG_LEVEL >= LEVEL_DEBUG) {
Log.d(tag, msg);
} else if ('i' == level && MYLOG_LEVEL >= LEVEL_INFO) {
Log.i(tag, msg);
} else {
Log.v(tag, msg);
}
if (MYLOG_WRITE_TO_FILE) {
writeLogToFile(String.valueOf(level), tag, msg);
}
}
}
private static String initPath() {
if (TextUtils.isEmpty(MYLOG_PATH)) {
if (FileUtils.isSDCardAvailable()) {
MYLOG_PATH = FileUtils.getRootPath() + "/logs";
File dir = new File(MYLOG_PATH);
if (!dir.exists()) {
dir.mkdirs();
}
}
}
return MYLOG_PATH;
}
/** * 打开日志文件并写入日志 **/
private synchronized static void writeLogToFile(String mylogtype, String tag, String text) {
Date nowtime = new Date();
StringBuilder builder = new StringBuilder();
builder.append(myLogSdf.format(nowtime)).append(" ").append(mylogtype).append(" ")
.append(tag).append(" ").append(text);
File file = new File(initPath(), MYLOG_FILE_NAME + "_" + logfileSdf.format(nowtime) + ".log");
FileWriter filerWriter = null;
BufferedWriter bufWriter = null;
try {
filerWriter = new FileWriter(file, true);//true 不进行覆盖
bufWriter = new BufferedWriter(filerWriter);
bufWriter.write(builder.toString());
bufWriter.newLine();
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.close(bufWriter);
IOUtils.close(filerWriter);
}
}
/** * 删除过期的日志文件 */
public static void delOutOfDateLogs() {
long needDeltime = getDateBefore().getTime();
File[] files = (new File(MYLOG_PATH)).listFiles();
if (files.length > 0) {
for (File file : files) {
long lastModified = file.lastModified();
if (lastModified < needDeltime) {
LogUtils.d(TAG, "===== delOutOfDateLogs:" + file.getPath());
file.delete();
}
}
}
}
/** * 得到现在时间前的几天日期,用来得到需要删除的日志文件名 */
private static Date getDateBefore() {
Date nowtime = new Date();
Calendar now = Calendar.getInstance();
now.setTime(nowtime);
now.set(Calendar.DATE, now.get(Calendar.DATE)
- MYLOG_FILE_SAVE_DAYS);
return now.getTime();
}
}
代码:
package ***;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
/** * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序,并记录发送错误报告. * @author huangyk * created at 2015/10/8 */
public class ExceptionHandler implements UncaughtExceptionHandler {
public static final String TAG = "ExceptionHandler";
public static final String PATH = "/sdcard/idong/";
//系统默认的UncaughtException处理类
private UncaughtExceptionHandler mDefaultHandler;
//CrashHandler实例
private static ExceptionHandler INSTANCE = new ExceptionHandler();
//程序的Context对象
private Context mContext;
//用来存储设备信息和异常信息
private Map<String, String> infos = new HashMap<String, String>();
//用于格式化日期,作为日志文件名的一部分
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
/** 保证只有一个CrashHandler实例 */
private ExceptionHandler() {
}
/** 获取CrashHandler实例 ,单例模式 */
public static ExceptionHandler getInstance() {
return INSTANCE;
}
/** * 初始化 * * @param context */
public void init(Context context) {
mContext = context;
//获取系统默认的UncaughtException处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
//设置该CrashHandler为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
/** * 当UncaughtException发生时会转入该函数来处理 */
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
//如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} 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, "很抱歉,程序出现异常,即将退出。", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
//收集设备参数信息
collectDeviceInfo(mContext);
//保存日志文件
saveCrashInfo2File(ex);
return true;
}
/** * 收集设备参数信息 * @param ctx */
public void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
Log.e(TAG, "an error occured when collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
Log.d(TAG, field.getName() + " : " + field.get(null));
} catch (Exception e) {
Log.e(TAG, "an error occured when collect crash 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 {
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = "crash-" + time + ".log";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String path = PATH;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName, true);
fos.write(sb.toString().getBytes());
fos.close();
}
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
}
return null;
}
}
Application中实例化:
public class TreefrogApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// 开启全局捕获异常
ExceptionHandler exceptinHandler = ExceptionHandler.getInstance();
exceptinHandler.init(getApplicationContext());
}
}