[mobilesafe] 09_实际开发过程中Bug的处理-上报bug

Android 4.0

实际开发过程中Bug的处理-上报bug
程序异常终止的处理,强行停止,程序崩溃处理,UncaughtExceptionHandler

bug处理流程:
1、在有bug的程序中,重写未捕获异常的默认handler
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
2、实现该handler,将错误给保存下来,或者上传到服务器上
3、然后该handler自己杀死自己
Process.killProcess(Process.myPid());
1、有bug的程序
public class MainActivity extends Activity {
    String s;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        
        s.equals("11");
    }
}
2、重写未捕获异常的默认处理器
MyUncaughtExceptionHandler.java
package cn.zengfansheng.bugreport;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;
import android.os.Environment;
import android.os.Process;
public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        System.out.println("发生了未捕获的异常,但是被哥被捕获了...");
        try {
            // 1、StringWriter
//            StringWriter sWriter = new StringWriter();
//            PrintWriter err = new PrintWriter(sWriter);
//            ex.printStackTrace(err);
//            
//            File file = new File(Environment.getExternalStorageDirectory(), "error.log");
//            FileOutputStream fos = new FileOutputStream(file);
//            fos.write(sWriter.toString().getBytes());
//            fos.close();
            
            // 2、
            File file =  new File(Environment.getExternalStorageDirectory(), "error1.log");
            OutputStream out = new FileOutputStream(file );
            PrintStream err = new PrintStream(out );
            ex.printStackTrace(err );
            out.close();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 自己杀死自己,自杀 早点重新投胎
            Process.killProcess(Process.myPid());
        }
    }
}