"Android Live" processing crash exception in Android

Source: Internet
Author: User

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 PR Esent.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 and RoidManifest.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 () {(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";//system default UNC Aughtexception Processing class Private Thread.uncaughtexceptionhandler mdefaulthandler;//Crashhandler instance private static Crashhandler INSTANCE = new Crashhandler ();//Program Context object private Context mcontext;//used to store device information and exception information private map< String, string> infos = new hashmap<string, string> ();//For formatting dates, as part of the log file name private SimpleDateFormat Formatter = new SimpleDateFormat ("Yyyy-mm-dd-hh-mm-ss");/** guarantees that there is only one Crashhandler instance */private Crashhandler () {}/** Get Crashhandler instance, Singleton mode */public static Crashhandler getinstance () {return INSTANCE;} /** * Initialize * * @param context */public void init (context context) {Mcontext = context;//get system default Uncaughtexception processor Mdefau Lthandler = Thread.getdefaultuncaughtexceptionhandler ();// Set the Crashhandler as the program's default processor Thread.setdefaultuncaughtexceptionhandler (this);} /** * When uncaughtexception occurs, it is transferred to the function to process */@Overridepublic void uncaughtexception (thread thread, ThroWable ex) {if (!handleexception (ex) && Mdefaulthandler! = null) {// Assume that the user does not handle the system by letting the default exception handler handle mdefaulthandler.uncaughtexception (thread, ex); try {thread.sleep);} catch ( Interruptedexception e) {log.e (TAG, "error:", e);} Exit Program Android.os.Process.killProcess (Android.os.Process.myPid ()); System.exit (1);} else {try {thread.sleep,} catch (Interruptedexception e) {log.e (TAG, "error:", e);} Exit program ((crashapplication) mcontext). Finishacts ();};} /** * self-defined error handling, collect error messages to send error reports and other operations are complete here. * * @param ex * @return true: It is assumed that the exception information was processed; otherwise, 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, "very sorry, the program is abnormal, is about to exit.", Toast.length_long). Show (); Looper.loop ();}}. Start ();//Collection Device parameter information collectdeviceinfo (mcontext);//Save log file Savecrashinfo2file (ex); return true;} /** * Collection Device reference 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 if 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 error message to file * * @param ex * @return return file name, convenient to transfer file to server */private string Savecrashinfo2file (Throwable ex) {string Buffer 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 + "-" + 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;}}




"Android Live" processing crash exception in Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.