如何在没有ADB的情况下转储Android logcat?

时间:2015-04-07 16:35:02

标签: android adb logcat

我知道我可以use adb to dump logcat to a file,但我遇到了为我的设备配置驱动程序的问题(Moverio BT-200)。因此,adb无法找到该设备,然后无法检索该logcat。

我的应用程序在开始时崩溃,所以我不能retrieve the logcat programmatically。我在其他一些设备(使用Android 5.1和4.4.2)上测试了我的应用程序,并且它运行正常,所以我认为它是旧版Android(4.0.3)的问题;但是Android Studio没有给我任何关于API版本的警告。

还有其他方法可以转储logcat输出吗?

2 个答案:

答案 0 :(得分:0)

您可以通过程序转储logcat:

Runtime.getRuntime().exec("logcat -v time -f /sdcard/mylog.log -d");

我喜欢将此与Thread.setDefaultUncaughtExceptionHandler结合使用,将所有未捕获的异常捕获到回调中。在回调中,我转储日志,然后再次抛出异常让应用程序崩溃。

答案 1 :(得分:0)

感谢Randy的建议,我使用类似的旧代码将异常记录到文件中(我尝试使用运行时exec,但它只生成一个空文件)。

以下是我使用的代码:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread t, Throwable e) {
        File logFile = new File("/any/directory/logFile.log");
        PrintWriter out = null;

        try{
            if(!logFile.exists()){
                try {
                    if(!logFile.createNewFile())
                        Log.e(TAG, "Some error creating log file " + logFile.getAbsolutePath());
                } catch (IOException ex) {
                    Log.e(TAG, "IoException creating logFile: " + ex.getMessage());
                    ex.printStackTrace();
                }               
            }

            out = new PrintWriter(new BufferedWriter(new FileWriter(logFile, true)));
            out.println(
                new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss.SSS", Locale.getDefault()).format(new Date()) + "\t" +
                TAG + "\t" +
                "Thread " + t + " throws exception: " + e
            );
            if(e != null)
                e.printStackTrace(out);
            out.flush();
        } catch (IOException ex) {
            Log.e(TAG, "IoException writing logFile: " + ex.getMessage());
            ex.printStackTrace();
        } finally {
            if(out != null)
                out.close();
        }
    });
}