将Logcat保存到安卓设备中的文本文件

2022-09-01 05:32:33

我在Android设备中运行应用程序时发现了一些崩溃,这在模拟器中没有显示。所以我需要将Logcat保存在设备内存或SD卡的文本文件中。你能给我建议一个好的方法来做到这一点吗?


答案 1

在应用开头使用应用程序类。这允许正确的文件和日志处理。

下面的代码在以下位置创建一个日志文件:

/ExternalStorage/MyPersonalAppFolder/logs/logcat_XXX.txt

XXX 是当前时间(以毫秒为单位)。每次运行应用时,都会创建一个新的logcat_XXX.txt文件。

public class MyPersonalApp extends Application {

    /**
     * Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.
     */
    public void onCreate() {
        super.onCreate();

        if ( isExternalStorageWritable() ) {

            File appDirectory = new File( Environment.getExternalStorageDirectory() + "/MyPersonalAppFolder" );
            File logDirectory = new File( appDirectory + "/logs" );
            File logFile = new File( logDirectory, "logcat_" + System.currentTimeMillis() + ".txt" );

            // create app folder
            if ( !appDirectory.exists() ) {
                appDirectory.mkdir();
            }

            // create log folder
            if ( !logDirectory.exists() ) {
                logDirectory.mkdir();
            }

            // clear the previous logcat and then write the new one to the file
            try {
                Process process = Runtime.getRuntime().exec("logcat -c");
                process = Runtime.getRuntime().exec("logcat -f " + logFile);
            } catch ( IOException e ) {
                e.printStackTrace();
            }

        } else if ( isExternalStorageReadable() ) {
            // only readable
        } else {
            // not accessible
        }
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if ( Environment.MEDIA_MOUNTED.equals( state ) ) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available to at least read */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if ( Environment.MEDIA_MOUNTED.equals( state ) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals( state ) ) {
            return true;
        }
        return false;
    }
}

您需要在 .manifest 文件中提供应用程序类的正确权限和名称:

<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:name=".MyPersonalApp"
    ... >

编辑:

如果您只想保存某些特定活动的日志。

取代:

process = Runtime.getRuntime().exec("logcat -f " + logFile);

跟:

process = Runtime.getRuntime().exec( "logcat -f " + logFile + " *:S MyActivity:D MyActivity2:D");

答案 2
adb shell logcat -t 500 > D:\logcat_output.txt

转到终端/命令提示符并导航到包含adb的文件夹(如果尚未将其添加到环境变量中),然后粘贴此命令。

t 是您需要查看的数字行

D:\logcat_output.txt是存储 logcat 的位置。


推荐