Android phone models and versions on the market today are too many to fully adapt to almost impossible, then how to get other players error information! Here we are going to redefine the crash processing class for the system.
First we create a new Customcrashhandler class to implement the Uncaughtexceptionhandler interface, overriding the callback method void Uncaughtexception (thread thread, Throwable ex )
PackageCom.example.admin.crashchuli;ImportAndroid.content.Context;ImportAndroid.content.pm.PackageInfo;ImportAndroid.content.pm.PackageManager;ImportAndroid.os.Build;ImportAndroid.os.Environment;ImportAndroid.os.Looper;ImportAndroid.util.Log;ImportAndroid.widget.Toast;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.PrintWriter;ImportJava.io.StringWriter;ImportJava.text.SimpleDateFormat;ImportJava.util.Date;ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.TimeZone;/** * Customize the system's crash capture class, use Toast to replace the system's dialog box * To save the software version information, device information, error information in the SD card, easy to upload to the server * @author ls * / Public class Customcrashhandler implements Thread. Uncaughtexceptionhandler { Private Static FinalString TAG ="Activity";PrivateContext Mcontext;Private Static FinalString sdcard_root = Environment.getexternalstoragedirectory (). toString ();Private StaticCustomcrashhandler minstance =NewCustomcrashhandler ();Private Customcrashhandler(){}/** * Singleton mode to ensure that only one Customcrashhandler instance exists * @return * / Public StaticCustomcrashhandlergetinstance(){returnMinstance; }/** * When an exception occurs, the system callback function, we handle some operations here * / @Override Public void uncaughtexception(thread thread, throwable ex) {//Save some information to SDcardSAVAINFOTOSD (Mcontext, ex);//Prompt user program to exit soonShowtoast (Mcontext,"I'm sorry, the program is in an unusual situation and will exit! ");Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {E.printstacktrace (); }//Android.os.Process.killProcess (Android.os.Process.myPid ());//System.exit (1); //Perfect Exit procedure methodExitapputils.getinstance (). exit (); }/** * Set custom crash processing for our applications */ Public void Setcustomcrashhanler(Context context) {Mcontext = context; Thread.setdefaultuncaughtexceptionhandler ( This); }/** * Display the prompt message, you need to show toast in thread * @param context * @param msg * * Private void Showtoast(FinalContext Context,FinalString msg) {NewThread (NewRunnable () {@Override Public void Run() {looper.prepare (); Toast.maketext (Context, MSG, Toast.length_long). Show (); Looper.loop (); }}). Start (); }/** * Get some simple information, software version, mobile phone version, model number and other information stored in HashMap * @param context * @return * * PrivateHashmap<string, string>Obtainsimpleinfo(Context context) {hashmap<string, string> map =NewHashmap<string, string> (); Packagemanager Mpackagemanager = Context.getpackagemanager (); PackageInfo Mpackageinfo =NULL;Try{mpackageinfo = Mpackagemanager.getpackageinfo (Context.getpackagename (), packagemanager.get_activities); }Catch(Packagemanager.namenotfoundexception e) {E.printstacktrace (); } map.put ("Versionname", mpackageinfo.versionname); Map.put ("Versioncode",""+ Mpackageinfo.versioncode); Map.put ("MODEL",""+ Build.model); Map.put ("Sdk_int",""+ Build.VERSION.SDK_INT); Map.put ("PRODUCT",""+ build.product);returnMap }/** * Get error messages not captured by the system * @param throwable * @return * * PrivateStringObtainexceptioninfo(Throwable throwable) {StringWriter Mstringwriter =NewStringWriter (); PrintWriter Mprintwriter =NewPrintWriter (Mstringwriter); Throwable.printstacktrace (Mprintwriter); Mprintwriter.close (); LOG.E (TAG, mstringwriter.tostring ());returnMstringwriter.tostring (); }/** * Save acquired software information, device information and error messages in SDcard * @param context * @param ex * @return */ PrivateStringSavainfotosd(context context, throwable ex) {String FileName =NULL; StringBuffer SB =NewStringBuffer (); for(Map.entry<string, string> entry:obtainsimpleinfo (context). EntrySet ()) {String key = Entry.getkey (); String value = Entry.getvalue (); Sb.append (Key). Append (" = "). Append (Value). Append ("\ n"); } sb.append (Obtainexceptioninfo (ex));if(Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {File dir =NewFile (sdcard_root + file.separator +"Crash"+ File.separator);if(! dir.exists ()) {Dir.mkdir (); }Try{fileName = dir.tostring () + File.separator + pasertime (System.currenttimemillis ()) +". Log"; FileOutputStream fos =NewFileOutputStream (FileName); Fos.write (Sb.tostring (). GetBytes ()); Fos.flush (); Fos.close (); }Catch(Exception e) {E.printstacktrace (); } }returnFileName; }/** * Converts the number of milliseconds to YYYY-MM-DD-HH-MM-SS format * @param milliseconds * @return * * PrivateStringPasertime(Longmilliseconds) {System.setproperty ("User.timezone","Asia/shanghai"); TimeZone TZ = Timezone.gettimezone ("Asia/shanghai"); Timezone.setdefault (TZ); SimpleDateFormat format =NewSimpleDateFormat ("Yyyy-mm-dd-hh-mm-ss"); String times = Format.format (NewDate (milliseconds));returnTimes }}
Of course don't forget to add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
Then there is the crash processing class that is set for it in the OnCreate () method in the overridden application class.
/** * Created by ls on 2017/4/30. */publicclass MyApplication extends Application{ @Override publicvoidonCreate() { super.onCreate(); CustomCrashHandler mCustomCrashHandler = CustomCrashHandler.getInstance(); mCustomCrashHandler.setCustomCrashHanler(getApplicationContext()); }}
Remember to set application in the manifest file that's all you have to say.
And then write a blank pointer exception.
publicclass MainActivity extends BaseActivity { TextView mTextView; @Override protectedvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView.setText("crash"); }}
Then we can see in the folder we set up below we want to log txt file, the rest I will not say is simply upload to the server,
By the way, Exitapputils is in order to set the perfect exit because of the abnormal time will blink a few times or a little cell phone directly out of this certainly not, so use exitapputils to control, Of course, not all the activity is written, so it's written in baseactivity, and then the rest of the inheritance is good.
PackageCom.example.admin.crashchuli;Importandroid.app.Activity;ImportAndroid.os.Bundle;/** * Created by admin on 2017/4/30. * * Public class baseactivity extends Activity { @Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Exitapputils.getinstance (). Addactivity ( This); }@Override protected void OnDestroy() {Super. OnDestroy (); Exitapputils.getinstance (). Delactivity ( This); }}
Android Basics---Rewrite system crash processing class save upload and Perfect Exit program method