android設置缺省的異常捕獲器

import java.lang.Thread.UncaughtExceptionHandler;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    Button tv = (Button)this.findViewById(R.id.btn_make_crash);
tv.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Log.i("xxx", "make null pointer exception");
        String str = null;
        str.length();

    }
});

    Button reg = (Button)this.findViewById(R.id.btn_reg);
    reg.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Log.i("jklxxx", "reg ");
            Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler(  

                    MainActivity.this.getApplicationContext()));            
        }

});
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class DefaultExceptionHandler implements UncaughtExceptionHandler {  



    private Context act = null;  



    public DefaultExceptionHandler(Context act) {  

       this.act = act;  

    }  

    @Override  

    public void uncaughtException(Thread thread, Throwable ex) {  

        Log.i("jklxxx", "catch exception");
        //ex.printStackTrace();

        //android.os.Process.killProcess(android.os.Process.myPid());
        //System.exit(0);
    }  


}  

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章