正在尝试将logcat保存到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();
}
}
}

我的文件路径.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对象不为null,但进程没有在文件中写入任何内容,也没有创建文件。

我正在使用一个带有API 30的模拟器。

私有静态最终字符串APP_DIRECTORY=Environment.getExternalStorageDirectory((+"MYAPPFOLDER";;

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

更改为:

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

最新更新