未捕获异常,现实程序崩溃闪退

    碰到程序崩溃时,闪退效果,不会提示"xxx程序异常,退出程序"。这样的效果就要使用到未捕获异常来实现,这里记录了我的一个写法。其实原理很简单,设置程序的未捕获异常监听,实现监听的一个方法,在该方法中现实直接没有提示的退出程序。


  1. 捕获异常工具类

package com.tdh.http;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import android.content.Context;
import android.util.Log;

public class OtherExceptionsHandler implements UncaughtExceptionHandler {

    private static Context mAppContext; //上下文对象
    private static OtherExceptionsHandler instance;  //单例引用,这里我们做成单例的,因为我们一个应用程序里面只需要一个UncaughtExceptionHandler实例
    
    private OtherExceptionsHandler(){}
    
    public synchronized static OtherExceptionsHandler getInstance(){  //同步方法,以免单例多线程环境下出现异常
        if (instance == null){
            instance = new OtherExceptionsHandler();
        }
        return instance;
    }
    
    /**需要上下文对象的初始化*/
    public synchronized OtherExceptionsHandler init(Context context){  //初始化,把当前对象设置成UncaughtExceptionHandler处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
        mAppContext = context.getApplicationContext();
        return instance;
    }
    
    public synchronized OtherExceptionsHandler init(){  //初始化,把当前对象设置成UncaughtExceptionHandler处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
        return instance;
    }
    
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
    	if(mAppContext != null){
    		otherException(thread, ex, mAppContext);
    	}
    	otherException(thread, ex);
    }
    
    /**
     * 处理异常的一般情况
     * @param thread
     * @param ex
     */
    public void otherException(Thread thread, Throwable ex){
    	StringWriter sw = new StringWriter();  
    	ex.printStackTrace(new PrintWriter(sw, true));
    	
    	Log.e("uncaughtException", "thread: " + thread
    			+ " name: " + thread.getName()
    			+ " id: " + thread.getId()
    			+ "exception: " + Log.getStackTraceString(ex));
    	
    	System.exit(0);
    }
    
    /**
     * 处理异常的特殊情况,一般是需要用到上下文对象context
     * @param thread
     * @param ex
     * @param context
     */
    public void otherException(Thread thread, Throwable ex, Context context){
    	
    }
}


2.在Application中初始化

package com.tdh.http;

import android.app.Application;

public class MyApplication extends Application {
	@Override
	public void onCreate() {
		super.onCreate();
		OtherExceptionsHandler.getInstance().init();
	}
}


3.在AndroidManifest.xml中配置

<application
        android:name="com.tdh.http.MyApplication"
        ... >


4.在activity中测试

findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
	@Override
	public void onClick(View v) {
		String e = null;
		e.getBytes();		
	}
});