0

我已经在异常可能的地方实现了 try catch。android OS[Database Exception, Permission and other exception]会抛出不同的其他异常。我想将这些错误日志数据写入文件{只有我们的应用程序崩溃}。

我已经有了将给定数据写入文件的代码。我只想知道如何从android进程中获取错误日志。

如果发生任何崩溃,则应用实例不可用。而且我不知道调用获取错误日志方法的确切位置。对此。请帮助我。

4

1 回答 1

0

在您的应用程序类中,您可以针对未处理的异常进行初始化。回调方法将有一个可抛出的对象。从这个对象我们可以得到崩溃日志数据,然后将相同的数据写入文件。

应用类:

public class MyApplication extends Application {
    // uncaught exception handler variable
    private UncaughtExceptionHandler defaultUEH;

    public MyApplication() {
        defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

        // setup handler for uncaught exception
        Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
    }

    // handler listener
    private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
                        //To write the crash log data to file
            AppUtil.getInstance().writeActivityLogToFile(true,
                    getErrorMessgae(ex));

            // re-throw critical exception further to the os (important) to handle
            defaultUEH.uncaughtException(thread, ex);
            // System.exit(2);
        }
    };

    /**
     * To get the crash log message from throwable object
     * 
     * @param e
     *            - throwable exception object
     * @return - the crash log
     */
    private String getErrorMessgae(Throwable e) {
        StackTraceElement[] stackTrackElementArray = e.getStackTrace();
        String crashLog = e.toString() + "\n\n";
        crashLog += "--------- Stack trace ---------\n\n";
        for (int i = 0; i < stackTrackElementArray.length; i++) {
            crashLog += "    " + stackTrackElementArray[i].toString() + "\n";
        }
        crashLog += "-------------------------------\n\n";

        // If the exception was thrown in a background thread inside
        // AsyncTask, then the actual exception can be found with getCause
        crashLog += "--------- Cause ---------\n\n";
        Throwable cause = e.getCause();
        if (cause != null) {
            crashLog += cause.toString() + "\n\n";
            stackTrackElementArray = cause.getStackTrace();
            for (int i = 0; i < stackTrackElementArray.length; i++) {
                crashLog += "    " + stackTrackElementArray[i].toString()
                        + "\n";
            }
        }
        crashLog += "-------------------------------\n\n";
        return crashLog;
    }
}

在您的清单中的以下标记中声明您的应用程序类:

<application
    android:name=".application.FleetLOCApplication"
    ......>
于 2015-05-31T11:48:40.327 回答