运用Application捕获整个程序的异常
aide吧
全部回复
仅看楼主
level 11
初始状态0 楼主
在做软件时,最头疼的就是闪退了。闪退原因是什么?不知道,要去查Logcat。如果发布后遇到闪退怎么办呢?用户是不去查Logcat的(也没几个人知道这东西),难道你要把所有的代码加上try-catch吗?这太蠢了!用我这种方法,可以一次性捕获整个程序的异常!不管什么线程,不管什么错误,Exception还是Error还是Throwable,都会捕获!
2015年06月12日 13点06分 1
level 11
初始状态0 楼主
首先,创建一个新的类,接口Thread.UncaughtExceptionHandler(因为流量就不发图了)
public class ExceptionHandler implements Thread.UncaughtExceptionHandler
{
@Override
public void uncaughtException(Thread p1, Throwable p2)
{
}
}
2015年06月12日 13点06分 2
level 11
初始状态0 楼主
使用单例模式,防止重复
private static ExceptionHandler exceptionHandler;
private ExceptionHandler()
{}
public static ExceptionHandler getInstance()
{
if(exceptionHandler==null)
exceptionHandler=new ExceptionHandler();
return exceptionHandler;
}
2015年06月12日 13点06分 3
level 11
初始状态0 楼主
添加init方法进行初始化
private boolean inited=false;
private Context ctx;
private Thread.UncaughtExceptionHandler defaultHandler;
public void init(Context ctx)
{
if(inited)return;
this.ctx=ctx;
defaultHandler=Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
2015年06月12日 13点06分 4
level 11
初始状态0 楼主
然后我们重写uncaughtException方法
@Override
public void uncaughtException(Thread p1,Throwable p2)
{
//p1:出错线程
//p2:错误
StringWriter stringWriter=new StringWriter();
PrintWriter printWriter=new PrintWriter(stringWriter);
p2.printStackTrace(printWriter);
//保存错误
String filename=Long.toHexString(System.currentTimeMillis());
File parent=ctx.getDir("error",0);
File file=new File(parent,filename);
try{
FileOutputStream fos=new FileOutputStream(file);
fos.write(stringWriter.toString().getBytes());
fos.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
2015年06月12日 13点06分 5
level 11
初始状态0 楼主
写一个类,继承Application
public class myApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
ExceptionHandler.getInstance().init(this);
}
}
2015年06月12日 13点06分 6
level 11
初始状态0 楼主
最后,AndroidManofest.xml要注册
<application
android:name="myApplication的路径"
……>
以下省略
2015年06月12日 14点06分 7
level 11
初始状态0 楼主
抛出异常后就会把异常保存到/data/data/包名/error/里,文件名为时间的十六进制字符串。
如果还需要系统的闪退效果,在uncaughtException方法最后面加一行defaultHandler.uncaughtException(p1,p2);
然后,自己再写几行代码,把错误发送到自己的服务器吧
2015年06月12日 14点06分 8
1