Friday, April 20, 2012

How to treat force close elegantly in Android ?

All android developer must have faced force close issue while developing an application.
Here is a method to catch that error and treat it elegantly.
This will create an error page kind of mechanism in your android application.So whenever your application is crashed user will not able to see that irritating pop up dialog. Instead of that app will display a predifned view to the user.
To make such kind of mechanism we need to make one error handler and an Activity class which will gain the view whenever the app gets forced closed.

import android.content.*;
import android.os.Process;

public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
    private final Context myContext;

    public UncaughtExceptionHandler(Context context) {
        myContext = context;

    public void uncaughtException(Thread thread, Throwable exception) {
        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));

        Intent intent = new Intent(myContext, CrashActivity.class);
        intent.putExtra(BugReportActivity.STACKTRACE, stackTrace.toString());

Above class will work as a listener for forced close error. You can see that Intent and startActivity is used to start the new Activity whenever app crashes. So it will start the activity named CrashActivity whenever app get crashed.For now I have passed the stack trace as an intent's extras.
Now because CrashActivity is a regualr Android Actitvity you can handle it in whatever way you want.
Now comes the important part i.e. How to catch that exception.
Though it is very simple. Copy following line of code in your each Activity just after the call of super method in your overriden onCreate method.

Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));
Your Activity may look something like this...
public class ForceClose extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));


No comments:

Post a Comment