Xamarin.android-Catching unhandled exception (global exception)

Source: Internet
Author: User

First, preface

If an unhandled exception occurs in Android, the program will Flash, which is a very bad user experience, many users will uninstall the app, so the unhandled exception should be avoided as much as possible.

There are some hard to avoid exceptions (such as IO, network, etc.) that should be captured in the code and handled accordingly to prevent the program from crashing.

But "no program is perfect", and all kinds of Android terminal also greatly increased the probability of abnormal appearance, even the powerful QQ, and so will not flash back!

At this point, you need to catch the unhandled exception globally and handle it. (Note: the processing in this article does not prevent app Flash )

Processing Method: Collect exception information, current scene [time, hardware parameters], upload to the server at the right time

role:1, easy to repair the next version of the Bug 2, easy to help users to solve the difficulties caused by the exception

Second, refer to the way of Java Android (this is the pit AH)

Xamarin.android can refer to Java Android code in a lot of times, so I implemented "catch unhandled exception" in the way Java Android did

[Obsolete] Public classCrashHandler:Thread.IUncaughtExceptionHandler {//system default Uncaughtexception processing class        PrivateThread.iuncaughtexceptionhandler Mdefaulthandler; //Crashhandler Instances        Private StaticCrashhandler INSTANCE =NewCrashhandler (); //context object for the program        PrivateContext Mcontext; /// <summary>        ///guaranteed only one Crashhandler instance/// </summary>        PrivateCrashhandler () {}/// <summary>        ///get Crashhandler instances, Singleton mode/// </summary>        /// <returns></returns>         Public StaticCrashhandler getinstance () {returnINSTANCE; }         PublicIntPtr Handle {Get{returnThread.CurrentThread (). Handle; }        }         Public voidDispose () { This.        Dispose (); }        /// <summary>        ///Initialize/// </summary>        /// <param name= "context" ></param>         Public voidInit (Context context) {Mcontext=context; //get the system default Uncaughtexception processorMdefaulthandler =Thread.defaultuncaughtexceptionhandler; //set the Crashhandler as the default processor for the programThread.defaultuncaughtexceptionhandler = This; }        ///when uncaughtexception occurs, it is transferred to the function to handle         Public voiduncaughtexception (thread thread, Throwable ex) {if(! HandleException (ex) && Mdefaulthandler! =NULL)            {                //let the system default exception handler handle if the user does not handlemdefaulthandler.uncaughtexception (thread, ex); }            Else            {                //Exit ProgramAndroid.OS.Process.KillProcess (Android.OS.Process.MyPid ()); Javasystem.exit (1); }        }        /// <summary>        ///Exception Handling/// </summary>        /// <param name= "ex" ></param>        /// <returns>Returns true if the exception information is handled, otherwise false.</returns>        Private BOOLHandleException (Throwable ex) {if(ex = =NULL)            {                return false; }            //handlers (important information such as recording exceptions, device information, time, etc.)//************            //TipsTask.run (() ={looper.prepare (); //can be replaced by more friendly hintsToast.maketext (Mcontext,"Sorry, the program is abnormal and is about to exit.", Toastlength.long).                Show ();            Looper.loop ();            }); //stop for a while and let the previous operation finishSystem.Threading.Thread.Sleep ( -); return true; }    }
View Code
[Application (Label ="MyApplication")]     Public classmyapplication:application { PublicMyApplication (IntPtr javareference, jnihandleownership transfer):Base(javareference, transfer) {} Public Override voidOnCreate () {Base.            OnCreate (); Crashhandler Crashhandler=crashhandler.getinstance ();        Crashhandler.init (ApplicationContext); }    }
View Code

Customize an exception handling class Crashhandler by implementing the Java.Lang.Thread.IUncaughtExceptionHandler interface and replace the Java.Lang.Thread.DefaultUncaughtExceptionHandl Er

When uncaughtexception occurs, it is transferred to the Uncaughtexception method in the Crashhandler class, where the exception is handled.

Then create an exception throw new Exception ("I am an exception!") "), I thought the program would enter the Uncaughtexception method in the Crashhandler class, but the result is not, that is, this way failed, why? Google found that Iuncaughtexceptionhandler can only capture the Dalvik runtime exception, mono runtime C # exception, this does not work.

So this way no, pit pits!

Third, the right way to capture

[Application (Label ="MyApplication")]     Public classmyapplication:application { PublicMyApplication (IntPtr javareference, jnihandleownership transfer):Base(javareference, transfer) {} Public Override voidOnCreate () {Base.            OnCreate (); //Registering unhandled Exception EventsAndroidenvironment.unhandledexceptionraiser + =Androidenvironment_unhandledexceptionraiser; //Crashhandler Crashhandler = Crashhandler.getinstance (); //Crashhandler.init (applicationcontext);        }        protected Override voidDispose (BOOLdisposing) {Androidenvironment.unhandledexceptionraiser-=Androidenvironment_unhandledexceptionraiser; Base.        Dispose (disposing); }        voidAndroidenvironment_unhandledexceptionraiser (Objectsender, Raisethrowableeventargs e)        {Unhandledexceptionhandler (e.exception, E); }        /// <summary>        ///Handling Unhandled Exceptions/// </summary>        /// <param name= "E" ></param>        Private voidUnhandledexceptionhandler (Exception ex, Raisethrowableeventargs e) {//handlers (important information such as recording exceptions, device information, time, etc.)//**************            //TipsTask.run (() ={looper.prepare (); //can be replaced by more friendly hintsToast.maketext ( This,"Sorry, the program is abnormal and is about to exit.", Toastlength.long).                    Show ();                Looper.loop ();            }); //stop for a while and let the previous operation finishSystem.Threading.Thread.Sleep ( -); E.handled=true; }    }
View Code

Register Unhandled Exception Event Androidenvironment.unhandledexceptionraiser + = Androidenvironment_unhandledexceptionraiser; Exception handling is performed in Androidenvironment_unhandledexceptionraiser.

Create an exception throw new Exception ("I am an exception!") "), and duly entered the Androidenvironment_unhandledexceptionraiser,ok, and succeeded!

Description: After catching the exception of the specific processing, is nothing more than reading hardware information, time, exception information, and save to the local, in the right time to upload to the service side, in order to highlight the focus, I do not realize here.

SOURCE download

Https://github.com/jordanqin/CatchException

Reference:

Http://forums.xamarin.com/discussion/4576/application-excepionhandler
http://blog.csdn.net/liuhe688/article/details/6584143

If you find the article helpful, you can click the "recommend" button next to it, which will give more people the opportunity to see

Xamarin.android-Catching unhandled exception (global exception)

Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

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.