在項(xiàng)目中,我們的應(yīng)用經(jīng)常會(huì)遇到崩潰的情況,如果你的項(xiàng)目已經(jīng)發(fā)送到了應(yīng)用市場(chǎng)上,那么應(yīng)用發(fā)生的崩潰開(kāi)發(fā)人員是開(kāi)不到的,所以我們要想辦法將異常信息傳到服務(wù)器上,便于開(kāi)發(fā)人員查看并作出修改。Google考慮到這一點(diǎn),也提供了Thread.UncaughtExceptionHandler接口來(lái)實(shí)現(xiàn)這一問(wèn)題。
創(chuàng)新互聯(lián)長(zhǎng)期為近1000家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開(kāi)放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為寬城企業(yè)提供專業(yè)的成都網(wǎng)站制作、做網(wǎng)站、外貿(mào)營(yíng)銷網(wǎng)站建設(shè),寬城網(wǎng)站改版等技術(shù)服務(wù)。擁有十多年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開(kāi)發(fā)。
創(chuàng)建Crash異常捕獲很簡(jiǎn)單,主要的步驟有:
1.創(chuàng)建BaseApplication繼承Application并實(shí)現(xiàn)Thread.UncaughtExceptionHandler
2.通過(guò)Thread.setDefaultUncaughtExceptionHandler(this)設(shè)置默認(rèn)的異常捕獲
3.最后在manifests中注冊(cè)創(chuàng)建的BaseApplication
一、異常捕捉的簡(jiǎn)單實(shí)用
public class BaseApplication extends Application implements Thread.UncaughtExceptionHandler { @Override public void onCreate() { super.onCreate(); //設(shè)置異常捕獲 CrashHandler catchHandler = CrashHandler.getInstance(); catchHandler.init(this); } }
二、CrashHandler(主要是實(shí)現(xiàn)uncaughtException方法)
public class CrashHandler implements UncaughtExceptionHandler { public static final String TAG = "CrashHandler"; // 系統(tǒng)默認(rèn)的UncaughtException處理類 private Thread.UncaughtExceptionHandler mDefaultHandler; // CrashHandler實(shí)例 private static CrashHandler instance; // 程序的Context對(duì)象 private Context mContext; // 用來(lái)存儲(chǔ)設(shè)備信息和異常信息 private Mapinfos = new HashMap (); // 用于格式化日期,作為日志文件名的一部分 private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); MyActivityLifecycleCallbacks mMyActivityLifecycleCallbacks = new MyActivityLifecycleCallbacks(); /** 保證只有一個(gè)CrashHandler實(shí)例 */ private CrashHandler() { } /** 獲取CrashHandler實(shí)例 ,單例模式 */ public static CrashHandler getInstance() { if (instance == null) instance = new CrashHandler(); return instance; } /** * 初始化 */ public void init(SspApplication context) { mContext = context; context.registerActivityLifecycleCallbacks(mMyActivityLifecycleCallbacks); // 獲取系統(tǒng)默認(rèn)的UncaughtException處理器 mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); // 設(shè)置該CrashHandler為程序的默認(rèn)處理器 Thread.setDefaultUncaughtExceptionHandler(this); } /** * 當(dāng)UncaughtException發(fā)生時(shí)會(huì)轉(zhuǎn)入該函數(shù)來(lái)處理 */ @Override public void uncaughtException(Thread thread, Throwable ex) { if (!handleException(ex) && mDefaultHandler != null) { // 如果用戶沒(méi)有處理則讓系統(tǒng)默認(rèn)的異常處理器來(lái)處理 mDefaultHandler.uncaughtException(thread, ex); } else { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // Log.e(TAG, "error : ", e); // } // 注意Thread.sleep(3000)和 SystemClock.sleep(3000)的區(qū)別 SystemClock.sleep(3000); // 退出程序 Log.i("=====killProcess======","=====killProcess======"); mMyActivityLifecycleCallbacks.removeAllActivities(); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(0); } } /** * 自定義錯(cuò)誤處理,收集錯(cuò)誤信息 發(fā)送錯(cuò)誤報(bào)告等操作均在此完成. * * @param ex * @return true:如果處理了該異常信息;否則返回false. */ private boolean handleException(Throwable ex) { Log.i("=====handleException======","=====handleException======"); if (ex == null) { return false; } // 收集設(shè)備參數(shù)信息 collectDeviceInfo(mContext); // 使用Toast來(lái)顯示異常信息 new Thread() { @Override public void run() { Looper.prepare(); Toast.makeText(mContext, "哎呀,出問(wèn)題了,我要暫時(shí)離開(kāi)了", Toast.LENGTH_SHORT).show(); Looper.loop(); } }.start(); // 保存日志文件 saveCatchInfo2File(ex); return true; } /** * 收集設(shè)備參數(shù)信息 * * @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); } } } /** * 保存錯(cuò)誤信息到文件中 * * @param ex * @return 返回文件名稱,便于將文件傳送到服務(wù)器 */ private String saveCatchInfo2File(Throwable ex) { StringBuffer sb = new StringBuffer(); for (Map.Entry 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()); SharedPreferences userInfo = mContext.getSharedPreferences( Constants.USER_SETTING_INFOS, 0); String loginName = userInfo.getString(Constants.USERNAME, ""); String fileName = "crash-" + time +"-"+loginName+ ".log"; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String path = "/mnt/sdcard/crash/"; File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } FileOutputStream fos = new FileOutputStream(path + fileName); fos.write(sb.toString().getBytes()); // 發(fā)送給開(kāi)發(fā)人員 sendCrashLog2PM(path + fileName); fos.close(); } return fileName; } catch (Exception e) { Log.e(TAG, "an error occured while writing file...", e); } return null; } /** * 將捕獲的導(dǎo)致崩潰的錯(cuò)誤信息發(fā)送給開(kāi)發(fā)人員 * * 目前只將log日志保存在sdcard 和輸出到LogCat中,并未發(fā)送給后臺(tái)。 */ private void sendCrashLog2PM(final String fileName) { if (!new File(fileName).exists()) { Toast.makeText(mContext, "日志文件不存在!", Toast.LENGTH_SHORT).show(); return; } else { new Thread(new Runnable() { @Override public void run() { Looper.prepare(); ArrayList picList = new ArrayList (); picList.add(fileName); SendEventPic sFile = new SendEventPic(mContext); UUIDGenerator generator = new UUIDGenerator(); String linkId = generator.generate().toString(); SharedPreferences userInfo = mContext.getSharedPreferences( Constants.USER_SETTING_INFOS, 0); String loginName = userInfo.getString(Constants.USERNAME, ""); String userId = userInfo.getString(Constants.USER_USERID_INFOS, ""); boolean isproblempic = sFile.isSendSuccess(picList, linkId, "crash_tng", "crash_tng", loginName, userId); Looper.loop(); } }).start(); } FileInputStream fis = null; BufferedReader reader = null; String s = null; try { fis = new FileInputStream(fileName); reader = new BufferedReader(new InputStreamReader(fis, "GBK")); while (true) { s = reader.readLine(); if (s == null) break; // 由于目前尚未確定以何種方式發(fā)送,所以先打出log日志。 Log.i("info", s.toString()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關(guān)閉流 try { reader.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
三、開(kāi)發(fā)過(guò)程中遇到的坑
如果在activity創(chuàng)建的時(shí)候崩潰的話,系統(tǒng)有時(shí)候(目前不確定什么情況下會(huì)重啟)會(huì)重啟當(dāng)前的activity,造成第二次的崩潰,如此循環(huán)……
所以,在應(yīng)用崩潰時(shí)要完全退出應(yīng)用。
public class MyActivityLifecycleCallbacks implements ActivityLifecycleCallbacks { private Listactivities = new LinkedList<>(); public static int sAnimationId = 0; @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { addActivity(activity); } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { removeActivity(activity); } /** * 添加Activity */ public void addActivity(Activity activity) { if (activities == null) { activities = new LinkedList<>(); } if (!activities.contains(activity)) { activities.add(activity);// 把當(dāng)前Activity添加到集合中 } } /** * 移除Activity */ public void removeActivity(Activity activity) { if (activities.contains(activity)) { activities.remove(activity); } if (activities.size() == 0) { activities = null; } } /** * 銷毀所有activity */ public void removeAllActivities() { for (Activity activity : activities) { if (null != activity) { activity.finish(); activity.overridePendingTransition(0, sAnimationId); } } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。