標籤:
在程式崩潰的時候 ,捕捉異常
步驟 首先在 activity的oncreat中調用 Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler( this.getApplicationContext(),crashInterface));
實現一個繼承UncaughtExceptionHandler的子類
1 public class DefaultExceptionHandler implements UncaughtExceptionHandler { 2 3 private Context act = null; 4 crashInterface crashInterface; 5 @Override 6 public void uncaughtException(Thread arg0, Throwable arg1) { Intent sIntent=new Intent(act , CrashActivity.class);27 sIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//必須帶上28 act.startActivity(sIntent);29 // crashInterface.finsh();30 //此處異常31 return;32 }33 34 public DefaultExceptionHandler(Context act,crashInterface crashInterface) { 35 this.crashInterface=crashInterface;36 this.act = act; 37 } 47 }
在需要捕獲異常的activity 中oncreat
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); view= getLayoutInflater().inflate(R.layout.activity_main, null); view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); setContentView(view); crashInterface crashInterface=new crashInterface() { @Override public void finsh() { // TODO Auto-generated method stub finish(); Process.killProcess(Process.myPid()); } }; Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler( this.getApplicationContext(),crashInterface)); }
1安卓筆記 異常捕捉