Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call a method before my application go to crash

Tags:

java

android

I'm a newbie in android and I always see Exception when I'm running my code. So, somebody can tell me Can I call a method before app go to crash anywhere without "try-catch".

like image 272
Ba Tới Xì Cơ Avatar asked Nov 13 '13 04:11

Ba Tới Xì Cơ


1 Answers

This would be better way to handle uncaught exception:

public class MyApplication extends Application {
@Override
    public void onCreate() {
        super.onCreate();
        appInitialization();
    }

    private void appInitialization() {
         defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
         Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
    }

    private UncaughtExceptionHandler defaultUEH;

    // handler listener
    private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            ex.printStackTrace();
            // TODO handle exception here
        }
    };
}

Application is a Base class for those who need to maintain global application state. And hence here, it will be a better place to handle such exceptions.

EDIT: The above code will handle uncaught exceptions if they are thrown inside UI thread. If an exception has occurred in worker thread, you can handle it in following way:

private boolean isUIThread(){
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }
// Setup handler for uncaught exceptions.
    Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
    {
        @Override
        public void uncaughtException (Thread thread, Throwable e)
        {
            handleUncaughtException (thread, e);
        }
    });

    public void handleUncaughtException(Thread thread, Throwable e) {
        e.printStackTrace(); // not all Android versions will print the stack trace automatically

        if (isUIThread()) {
            // exception occurred from UI thread
            invokeSomeActivity();

        } else {  //handle non UI thread throw uncaught exception

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    invokeSomeActivity();
                }
            });
        }
    }
like image 177
Shrikant Ballal Avatar answered Oct 18 '22 06:10

Shrikant Ballal