Im trying to save the content of logcat to a file, but it fails in Android 11. This is what I have:
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();
}
}
}
My 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>
And file provider:
<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>
I have debugged, and the logFile objet is not null, but the process is not writting anything in the file, and the file is not created.
I am using an emulator with API 30.
CodePudding user response:
private static final String APP_DIRECTORY = Environment.getExternalStorageDirectory() "/MYAPPFOLDER";
You cannot create folders in root of external storage with sdk 30 devices.
Change to:
private static final String APP_DIRECTORY =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) "/MYAPPFOLDER";