2012-12-28 116 views
2

我想为我的Android应用创建日志文件。我需要这个来调试应用程序的随机崩溃。为Android应用创建日志文件

我想创建一个函数,如果有一个unhandelled异常,总是会被调用。在日志中我想要异常消息。是否有任何类型的机制会在ANdroid的unhandelled异常中被调用?

+0

为什么logcat的输出还不够吗? – Henry

+0

@Henry该应用程序将安装在设备上,我想解决它为什么崩溃,通过将日志保存到SD卡 – Jaguar

+0

当设备通过USB连接到PC时,您可以获得此信息。即使您在碰撞后不久连接设备也能正常工作。 – Henry

回答

2

您可以使用UncaughtExceptionHandler如下图所示:

public class UncaughtExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler { 
    String Tag; 
    Context myContext; 
    public UncaughtExceptionHandler(Context context, String TAG) { 
     Tag = TAG; 
     myContext = context; 
    } 

    public void uncaughtException(Thread thread, Throwable exception) { 
     StringWriter sw = new StringWriter(); 
     exception.printStackTrace(new PrintWriter(sw)); 
     Logger.appendErrorLog(sw.toString(), Tag); 
     Intent intent = new Intent(myContext, ForceClose.class); 
     intent.putExtra(BugReportActivity.STACKTRACE, sw.toString()); 
     myContext.startActivity(intent); 
     Process.killProcess(Process.myPid()); 
     System.exit(10); 
    } 
} 

调用这个类中的第一个活动的onCreate()方法:

Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(getApplicationContext(),"FirstActivity")); 
2

尝试使用Android Android Acra

真的有那么请试试这个。

+0

谢谢,阿克拉是伟大的,但我想写我的代码。你能帮忙吗? – Jaguar

2

你可以写自己的日志猫,

当你的应用程序安装在真正的Android设备,而不是连接到Eclipse获得详细的调试信息

...

请检查教程:Read & Store Log-cat Programmatically in Android

您也可以查看this stack-overflow页面我已经发布解决方案代码片段和相关的有用信息。

相关问题