[Android practice] handle crash exceptions in Android and crash in android practice
public class MainActivity extends ActionBarActivity {public CrashApplication application;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);application = (CrashApplication) getApplication();application.addAct(this);Button button = null;button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stub}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}
public class CrashApplication extends Application {List<Activity> activityList = new ArrayList<Activity>();@Overridepublic void onCreate() {super.onCreate();CrashHandler crashHandler = CrashHandler.getInstance();crashHandler.init(getApplicationContext());}public void addAct(Activity a) {activityList.add(a);}public void delAct(Activity a) {activityList.remove(a);}public void finishActs() {for (Activity a : activityList) {if (null != a) {a.finish();}}android.os.Process.killProcess(android.os.Process.myPid());}}
Public class CrashHandler implements UncaughtExceptionHandler {public static final String TAG = "CrashHandler"; // The default UncaughtException class private Thread. uncaughtExceptionHandler mDefaultHandler; // CrashHandler INSTANCE private static CrashHandler INSTANCE = new CrashHandler (); // The Context object private Context mContext of the program; // private Map used to store device information and exception information <String, String> infos = new HashMap <String, String> (); // used to format the day Private SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd-HH-mm-ss") as part of the log file name "); /** ensure that only one CrashHandler INSTANCE */private CrashHandler () {}/ ** obtains the CrashHandler INSTANCE. Singleton mode */public static CrashHandler getInstance () {return INSTANCE ;} /*** initialize ** @ param context */public void init (Context context) {mContext = context; // obtain the default UncaughtException processor mDefaultHandler = Thread. getDefaultUncaughtExceptio NHandler (); // sets the CrashHandler as the default processor Thread of the program. setDefaultUncaughtExceptionHandler (this);}/*** when UncaughtException occurs, it will be transferred to this function for processing */@ Overridepublic void uncaughtException (Thread thread, Throwable ex) {if (! HandleException (ex) & mDefaultHandler! = Null) {// if the user does not process the mDefaultHandler, the system's default exception processor is used to process the mDefaultHandler. uncaughtException (thread, ex); try {Thread. sleep (3000);} catch (InterruptedException e) {Log. e (TAG, "error:", e) ;}// exit the android program. OS. process. killProcess (android. OS. process. myPid (); System. exit (1);} else {try {Thread. sleep (3000);} catch (InterruptedException e) {Log. e (TAG, "error:", e) ;}// exit the program (CrashApplication) mContext ). finishActs () ;};}/*** custom All the operations such as troubleshooting and collecting error messages and sending error reports are completed here. ** @ param ex * @ return true: If the exception information is processed, false is returned. */private boolean handleException (Throwable ex) {if (ex = null) {return false;} // use Toast to display exception information new Thread () {@ Overridepublic void run () {Looper. prepare (); Toast. makeText (mContext, "Sorry, the program encountered an exception and is about to exit. ", Toast. LENGTH_LONG ). show (); logoff. loop ();}}. start (); // collect device parameter information collectDeviceInfo (mContext); // Save the log file saveCrashInfo2File (e X); return true;}/*** collect device parameter information ** @ 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 );}}} /*** Save the error message to the file ** @ param ex * @ return returns the file name, which is convenient for transferring the file to the server */private String saveCrashInfo2File (Throwable ex) {StringBuffer sb = new StringBuffer (); for (Map. entry <String, String> entry: infos. entrySet () {String key = entry. getKey (); String value = entry. getValu E (); 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 + "-" + timestamp + ". log "; if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {String path = "/sdcard/crash /"; File dir = new File (path); if (! Dir. exists () {dir. mkdirs ();} FileOutputStream fos = new FileOutputStream (path + fileName); fos. write (sb. toString (). getBytes (); fos. close () ;}return fileName;} catch (Exception e) {Log. e (TAG, "an error occured while writing file... ", e) ;}return null ;}}