引起crash
public class MainActivity extends Activity {
Button click2Crash;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("Thread0", Thread.currentThread()+"");
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));
click2Crash = (Button)findViewById(R.id.clickToCrash);
click2Crash.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// String text = "aaa";
// System.out.print(text.charAt(10));
TextView t = null;
t.setText("abc");
}});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
自動捕捉stackTrace
public class UncaughtExceptionHandler implements
java.lang.Thread.UncaughtExceptionHandler {
private Context con_;
public UncaughtExceptionHandler(Context con){
this.con_ = con;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
System.err.println(sw);
Intent bugReportIntent = new Intent(con_, BugReportActivity.class);
bugReportIntent.putExtra(BugReportActivity.exceptionMsg, sw.toString());
con_.startActivity(bugReportIntent);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);// this is very important, we can got next activity
}
}
跳到一個新的activity
public class BugReportActivity extends Activity {
public static final String exceptionMsg = "exceptionMsg";
private TextView reportContent;
private Button sendMailBtn;
private Button cancelBtn;
protected void onCreate(Bundle bundle){
super.onCreate(bundle);
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));
// ACRA.init(getApplication());
// ACRA.getErrorReporter().putCustomData("formKey", "");
// ACRA.getErrorReporter().putCustomData("formKey", "");
//
setContentView(R.layout.bug_report);
reportContent = (TextView)findViewById(R.id.reportContent);
sendMailBtn = (Button)findViewById(R.id.sendMail);
cancelBtn = (Button)findViewById(R.id.cancel);
String sw = getIntent().getStringExtra(exceptionMsg);
reportContent.setText(sw);
initHandler();
}
private void initHandler(){
sendMailBtn.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Email will be sent to our helpdesk.", Toast.LENGTH_LONG).show();
}
});
cancelBtn.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
finish();
}
});
}
}