第一步是写异常的handler,CrashHander.java
public class CrashHander implements UncaughtExceptionHandler {
private Context mContext;
private static final String TAG = "CrashHander";
/**
* 单例模式
* 保证只有一个实例
*
*/
private CrashHander(){
}
private static class CrashHolder{
public static final CrashHander crashHander = new CrashHander();
}
public static CrashHander getInstance(){
return CrashHolder.crashHander;
// if (m_Instance == null)
// {
// lock(m_LockObject)
// {
// if (m_Instance == null)
// m_Instance = new Logger();
// }
// }
// return m_Instance;
}
public void init (Context context){
Thread.setDefaultUncaughtExceptionHandler(this);
this.mContext = context;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {//这个函数做俘获工作
// TODO Auto-generated method stub
String threadName = thread.getName();
if("main".equalsIgnoreCase(threadName)){
Log.d(TAG, "主线程"+ ex.toString());
}else {
Log.d(TAG, "子线程"+ threadName);
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}
第二步是继承application 然后调用前面的handler,ExceptionApplication.java
public class ExceptionApplication extends Application {
@Override
publicvoid onCreate() {
CrashHander.getInstance().init(getApplicationContext());
}
}
第三步是manifest.xml中指定这个应用的类
<application
android:name="com.××××.ExceptionApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
</application>