Detailed explanation for sending to the server based on the Android error message capture _android

Source: Internet
Author: User
Tags error handling exception handling http post throwable
Bugs and debug are the most frustrating things for programmers. The debug lasted 20 days and I was devastated. Tired, because of Android compatibility, different mobile phones will have different bugs out, and it is difficult to reproduce, so on the internet to find a similar save error log to file and upload to the server, the source is also shared out. I didn't add the code to upload to the server. I believe we all have ready-made code.

Let's start with the principle that, like Java EE's custom exception capture, the error is thrown up and then processed uniformly at the top. Here you can get exception message, save operation
The exception capture class is as follows:
Copy Code code as follows:

/**
* @author Stay
* Unify catch exception in application, save to file upload next time Open
*/
public class Crashhandler implements Uncaughtexceptionhandler {
/** whether to turn on log output, open in debug State,
* Off in release state to prompt for program performance
* */
public static Final Boolean DEBUG = true;
/** system default Uncaughtexception processing class * *
Private Thread.uncaughtexceptionhandler Mdefaulthandler;
/** Crashhandler Example * *
private static Crashhandler INSTANCE;
/** program's Context Object * *
Private context Mcontext;
/** guarantee Only one Crashhandler instance * *
Private Crashhandler () {}
/** get Crashhandler instance, single case mode * *
public static Crashhandler getinstance () {
if (INSTANCE = = null) {
INSTANCE = new Crashhandler ();
}
return INSTANCE;
}

/**
* Initialize, register the context object,
* Get the system default Uncaughtexception processor,
* Set the Crashhandler as the default processor for the program
*
* @param CTX
*/
public void init (context ctx) {
Mcontext = CTX;
Mdefaulthandler = Thread.getdefaultuncaughtexceptionhandler ();
Thread.setdefaultuncaughtexceptionhandler (this);
}

/**
* When uncaughtexception occurs, it is transferred to this function to handle
*/
@Override
public void uncaughtexception (thread thread, Throwable ex) {
if (!handleexception (ex) && mdefaulthandler!= null) {
If the user does not have the processing, let the system default exception handler handle
Mdefaulthandler.uncaughtexception (thread, ex);
else {//If you handled the exception yourself, the error dialog box will not pop up, you will need to quit the app manually
try {
Thread.Sleep (3000);
catch (Interruptedexception e) {
}
Android.os.Process.killProcess (Android.os.Process.myPid ());
System.exit (10);
}
}

/**
* Custom error handling, collecting error messages
* Send error report and so on to complete the operation here.
* Developers can customize the exception handling logic according to their own situation
* @return
* True means that the exception is handled, and the exception is not thrown up.
* False means not handling the exception (you can store the log information) and then handing it to the upper level (here's the system's exception handling) to handle it.
* Simply to be true does not eject the error prompt box, false will pop
*/
Private Boolean handleexception (final Throwable ex) {
if (ex = null) {
return false;
}
Final String msg = Ex.getlocalizedmessage ();
Final stacktraceelement[] stack = Ex.getstacktrace ();
Final String message = Ex.getmessage ();
Use Toast to display exception information
New Thread () {
@Override
public void Run () {
Looper.prepare ();
Toast.maketext (Mcontext, "program error:" + message, Toast.length_long). Show ();
You can create only one file, then all the way to the inside append and then send, so there will be duplicate information, the individual does not recommend
String fileName = "crash-" + system.currenttimemillis () + ". Log";
File File = new file (Environment.getexternalstoragedirectory (), fileName);
try {
FileOutputStream fos = new FileOutputStream (file,true);
Fos.write (Message.getbytes ());
for (int i = 0; i < stack.length; i++) {
Fos.write (Stack[i].tostring (). GetBytes ());
}
Fos.flush ();
Fos.close ();
catch (Exception e) {
}
Looper.loop ();
}

}.start ();
return false;
}

TODO send error report to server using HTTP Post no more details here
private void Postreport (file file) {
When uploading, you can also send the app version, the phone's model and other information sent by the server,
Android compatibility is well known, so it may not be the error of every phone, or the targeted to debug better
//    }
}

Registers the Exceptionhandler when application OnCreate, and can then be captured as soon as the program throws an exception.
Copy Code code as follows:

public class APP extends application{
@Override
public void OnCreate () {
Super.oncreate ();
Crashhandler Crashhandler = Crashhandler.getinstance ();
Register Crashhandler
Crashhandler.init (Getapplicationcontext ());
}
}
? public class Logactivity extends activity {
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
try {//create bug
File File = new file (Environment.getexternalstoragestate (), "Crash.bin");
FileInputStream fis = new FileInputStream (file);
byte[] buffer = new byte[1024];
Fis.read (buffer);
catch (Exception e) {
You can't throw an exception up here, if you want to save the log information, throw the runtime exception,
Let the custom handler to capture, unify the file to save the upload
throw new RuntimeException (e);
}
}
}

Note that if the catch does not throw after the default is handled by themselves, Exceptionhandler will not catch the exception.
To share a log wrapper class, just set the debug value here to let the console print out the log
Copy Code code as follows:

public class Debugutil {
public static final String TAG = "ICON";
public static Final Boolean DEBUG = true;

public static void Toast (context context,string content) {
Toast.maketext (context, content, Toast.length_short). Show ();
}

public static void Debug (String tag,string msg) {
if (DEBUG) {
LOG.D (tag, msg);
}
}

public static void Debug (String msg) {
if (DEBUG) {
LOG.D (TAG, msg);
}
}

public static void error (String tag,string error) {
LOG.E (tag, error);
}

public static void error (String error) {
LOG.E (TAG, error);
}
}

Related Article

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.