參考:
http://bigcat.easymorse.com/?p=1152
異常時(shí)寫入文件,下面是data/data中生成的文件:
http://bigcat.easymorse.com/?p=1152
package qianlong.qlmobile.ui;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Properties;
import java.util.TreeSet;
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.Looper;
import android.text.format.Time;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;
public class CrashHandler implements UncaughtExceptionHandler {
/** Debug Log tag*/
public static final String TAG = "CrashHandler";
/** 是否開啟日志輸出,在Debug狀態(tài)下開啟,
* 在Release狀態(tài)下關(guān)閉以提示程序性能
* */
public static final boolean DEBUG = false;
/** 系統(tǒng)默認(rèn)的UncaughtException處理類 */
private Thread.UncaughtExceptionHandler mDefaultHandler;
/** CrashHandler實(shí)例 */
private static CrashHandler INSTANCE;
/** 程序的Context對(duì)象 */
private Context mContext;
/** 使用Properties來保存設(shè)備的信息和錯(cuò)誤堆棧信息*/
private Properties mDeviceCrashInfo = new Properties();
private static final String VERSION_NAME = "versionName";
private static final String VERSION_CODE = "versionCode";
private static final String STACK_TRACE = "STACK_TRACE";
/** 錯(cuò)誤報(bào)告文件的擴(kuò)展名 */
private static final String CRASH_REPORTER_EXTENSION = ".cr";
/** 保證只有一個(gè)CrashHandler實(shí)例 */
private CrashHandler() {}
/** 獲取CrashHandler實(shí)例 ,單例模式*/
public static CrashHandler getInstance() {
if (INSTANCE == null) {
INSTANCE = new CrashHandler();
}
return INSTANCE;
}
/**
* 初始化,注冊(cè)Context對(duì)象,
* 獲取系統(tǒng)默認(rèn)的UncaughtException處理器,
* 設(shè)置該CrashHandler為程序的默認(rèn)處理器
* @param ctx
*/
public void init(Context ctx) {
mContext = ctx;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* 當(dāng)UncaughtException發(fā)生時(shí)會(huì)轉(zhuǎn)入該函數(shù)來處理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
//如果用戶沒有處理則讓系統(tǒng)默認(rèn)的異常處理器來處理
mDefaultHandler.uncaughtException(thread, ex);
} else {
//Sleep一會(huì)后結(jié)束程序
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Log.e(TAG, "Error : ", e);
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
/**
* 自定義錯(cuò)誤處理,收集錯(cuò)誤信息
* 發(fā)送錯(cuò)誤報(bào)告等操作均在此完成.
* 開發(fā)者可以根據(jù)自己的情況來自定義異常處理邏輯
* @param ex
* @return true:如果處理了該異常信息;否則返回false
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
Log.w(TAG, "handleException --- ex==null");
return true;
}
final String msg = ex.getLocalizedMessage();
if(msg == null) {
return false;
}
//使用Toast來顯示異常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast toast = Toast.makeText(mContext, "程序出錯(cuò),即將退出:\r\n" + msg,
Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
// MsgPrompt.showMsg(mContext, "程序出錯(cuò)啦", msg+"\n點(diǎn)確認(rèn)退出");
Looper.loop();
}
}.start();
//收集設(shè)備信息
collectCrashDeviceInfo(mContext);
//保存錯(cuò)誤報(bào)告文件
saveCrashInfoToFile(ex);
//發(fā)送錯(cuò)誤報(bào)告到服務(wù)器
//sendCrashReportsToServer(mContext);
return true;
}
/**
* 在程序啟動(dòng)時(shí)候, 可以調(diào)用該函數(shù)來發(fā)送以前沒有發(fā)送的報(bào)告
*/
public void sendPreviousReportsToServer() {
sendCrashReportsToServer(mContext);
}
/**
* 把錯(cuò)誤報(bào)告發(fā)送給服務(wù)器,包含新產(chǎn)生的和以前沒發(fā)送的.
* @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);
postReport(cr);
cr.delete();// 刪除已發(fā)送的報(bào)告
}
}
}
private void postReport(File file) {
// TODO 發(fā)送錯(cuò)誤報(bào)告到服務(wù)器
}
/**
* 獲取錯(cuò)誤報(bào)告文件名
* @param ctx
* @return
*/
private String[] getCrashReportFiles(Context ctx) {
File filesDir = ctx.getFilesDir();
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(CRASH_REPORTER_EXTENSION);
}
};
return filesDir.list(filter);
}
/**
* 保存錯(cuò)誤信息到文件中
* @param ex
* @return
*/
private String saveCrashInfoToFile(Throwable ex) {
Writer info = new StringWriter();
PrintWriter printWriter = new PrintWriter(info);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
String result = info.toString();
printWriter.close();
mDeviceCrashInfo.put("EXEPTION", ex.getLocalizedMessage());
mDeviceCrashInfo.put(STACK_TRACE, result);
try {
//long timestamp = System.currentTimeMillis();
Time t = new Time("GMT+8");
t.setToNow(); // 取得系統(tǒng)時(shí)間
int date = t.year * 10000 + t.month * 100 + t.monthDay;
int time = t.hour * 10000 + t.minute * 100 + t.second;
String fileName = "crash-" + date + "-" + time + CRASH_REPORTER_EXTENSION;
FileOutputStream trace = mContext.openFileOutput(fileName,
Context.MODE_PRIVATE);
mDeviceCrashInfo.store(trace, "");
trace.flush();
trace.close();
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing report file...", e);
}
return null;
}
/**
* 收集程序崩潰的設(shè)備信息
*
* @param ctx
*/
public void collectCrashDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
PackageManager.GET_ACTIVITIES);
if (pi != null) {
mDeviceCrashInfo.put(VERSION_NAME,
pi.versionName == null ? "not set" : pi.versionName);
mDeviceCrashInfo.put(VERSION_CODE, ""+pi.versionCode);
}
} catch (NameNotFoundException e) {
Log.e(TAG, "Error while collect package info", e);
}
//使用反射來收集設(shè)備信息.在Build類中包含各種設(shè)備信息,
//例如: 系統(tǒng)版本號(hào),設(shè)備生產(chǎn)商 等幫助調(diào)試程序的有用信息
//具體信息請(qǐng)參考后面的截圖
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
mDeviceCrashInfo.put(field.getName(), ""+field.get(null));
if (DEBUG) {
Log.d(TAG, field.getName() + " : " + field.get(null));
}
} catch (Exception e) {
Log.e(TAG, "Error while collect crash info", e);
}
}
}
}
用法:
//全局?jǐn)?shù)據(jù)存儲(chǔ)
public class App extends Application {
private final static float HEAP_UTILIZATION = 0.75f;
private final static int MIN_HEAP_SIZE = 6* 1024* 1024 ;
@Override
public void onCreate() {
super.onCreate();
// 異常處理,不需要處理時(shí)注釋掉這兩句即可!
CrashHandler crashHandler = CrashHandler.getInstance();
// 注冊(cè)crashHandler
crashHandler.init(getApplicationContext());
// 優(yōu)化內(nèi)存,以下非必須!
VMRuntime.getRuntime().setTargetHeapUtilization(HEAP_UTILIZATION);
VMRuntime.getRuntime().setMinimumHeapSize(MIN_HEAP_SIZE);
//changeMetrics(this);//修改屏幕Density
......
}
}
異常時(shí)寫入文件,下面是data/data中生成的文件:
//
private static final boolean DebugFlag = false;
//修改屏幕Density
public static void changeMetrics(Context context) {
DisplayMetrics curMetrics = context.getResources().getDisplayMetrics();
if(!DebugFlag) {
if (curMetrics.densityDpi == DisplayMetrics.DENSITY_HIGH) {
DisplayMetrics metrics = new DisplayMetrics();
metrics.scaledDensity = 1.0f;
metrics.density = 1.0f;
metrics.densityDpi = DisplayMetrics.DENSITY_MEDIUM;
metrics.xdpi = DisplayMetrics.DENSITY_MEDIUM;
metrics.ydpi = DisplayMetrics.DENSITY_MEDIUM;
metrics.heightPixels = curMetrics.heightPixels;
metrics.widthPixels = curMetrics.widthPixels;
context.getResources().getDisplayMetrics().setTo(metrics);
}
} else {
DisplayMetrics metrics = new DisplayMetrics();
metrics.scaledDensity = (float)(130/160.0);
metrics.density = (float)(130/160.0);
metrics.densityDpi = 130;
metrics.xdpi = 130;
metrics.ydpi = 130;
metrics.heightPixels = curMetrics.heightPixels;
metrics.widthPixels = curMetrics.widthPixels;
context.getResources().getDisplayMetrics().setTo(metrics);
}
}
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

