andoid处理未捕获异常

jopen 10年前

在某些意外的情况下,程序崩溃是我们不想看到的,这时我们可以使用未捕获异常,将日志写在文件里,记录错误信息,防止影响用户体验。

    package com.home.testuncatch;                import android.app.Activity;        import android.os.Bundle;        import android.view.View;        import android.view.View.OnClickListener;        import android.widget.Button;                import com.home.testuncaughtexception.R;                public class MainActivity extends Activity {            @Override            protected void onCreate(Bundle savedInstanceState) {                super.onCreate(savedInstanceState);                MyUncaughtExceptionHandler.getInstance().init();                setContentView(R.layout.main);                Button btn = (Button) findViewById(R.id.main_btn);                btn.setOnClickListener(new OnClickListener() {                            @Override                    public void onClick(View v) {                        String a = null;                        a.length();                    }                });            }        }  
</div> </div>


MyUncaughtExceptionHandler:

package com.home.testuncatch;        import java.io.PrintWriter;    import java.io.StringWriter;    import java.lang.Thread.UncaughtExceptionHandler;        public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {        private static MyUncaughtExceptionHandler instance;            public synchronized static MyUncaughtExceptionHandler getInstance() {            if (instance == null) {                instance = new MyUncaughtExceptionHandler();            }            return instance;        }            public void init() {            // 设置当前对象为默认的未捕获异常处理器            Thread.setDefaultUncaughtExceptionHandler(this);        }            @Override        public void uncaughtException(Thread t, Throwable e) {            StringWriter stackTrace = new StringWriter();            e.printStackTrace(new PrintWriter(stackTrace));            System.out.println(stackTrace);// 可将错误日志写在文件里            System.exit(10);        }        }  
</div> </div>