正在尝试将 logcat 保存到文件 Android 11

Trying to save logcat to file in Android 11

我试图将 logcat 的内容保存到文件中,但在 Android 11 中失败了。这就是我所拥有的:

private static final String APP_DIRECTORY = Environment.getExternalStorageDirectory() + "/MYAPPFOLDER";
private static final String LOGS_FOLDER = "/logs";
private static final String FLAVOR_FOLDER = "/" + BuildConfig.FLAVOR;

private static final int MAX_HOURS_IN_STORAGE = 360;

private static final int MAX_MB_IN_STORAGE = 100;

private static final int LOG_FILES_TO_SEND = 4;

private static Process process;

@Inject
public LogRegisterImpl() {
}

@Override
public void initLogRegister() throws ExternalMediaNotWritableException {

    checkExternalStorageWritable();

    if (process == null) {

        File appDirectory = new File(APP_DIRECTORY);
        File logDirectory = new File(appDirectory + LOGS_FOLDER);
        File flavorDirectory = new File(logDirectory + FLAVOR_FOLDER);
        // create app folder
        if (!appDirectory.exists()) {
            appDirectory.mkdirs();
        }
        // create log folder
        if (!logDirectory.exists()) {
            logDirectory.mkdirs();
        }

        // create flavor folder
        if (!flavorDirectory.exists()) {
            flavorDirectory.mkdirs();
        }
        ArrayList fileList = getAllFilesInDir(flavorDirectory);
        for (Object f : fileList) {
            deleteIfOlder((File) f, System.currentTimeMillis());
        }

        File logFile = new File(flavorDirectory, "log_" + DateUtils.getFileDate(new Date()) + "_" + BuildConfig.VERSION_NAME + "_" + BuildConfig.FLAVOR);

        // clear the previous logcat and then write the new one to the file
        try {
            Runtime.getRuntime().exec("logcat -c");
            process = Runtime.getRuntime().exec("logcat -v time -r " + 1024 * MAX_MB_IN_STORAGE + " -f " + logFile + " " + BuildConfig.APPLICATION_ID );
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

我的file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path name="my_files" path="/" />
<external-path name="logs" path="MYAPPFOLDER" />
</paths>

和文件提供者:

<provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
        <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
    </provider>

我已经调试过了,logFile对象不为空,但是进程没有在文件中写任何东西,也没有创建文件。

我正在使用 API 30.

的模拟器

private static final String APP_DIRECTORY = Environment.getExternalStorageDirectory() + "/MYAPPFOLDER";

您无法使用 sdk 30 设备在外部存储的根目录中创建文件夹。

更改为:

 private static final String APP_DIRECTORY = 
       Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/MYAPPFOLDER";