Android: Log Logcat to file while runtime

While I was developing a app for Android I was looking for a way to get the logcat output after testing my app without an USB  debugging connection. The following code allows you to store the logcat log in a file, accessible via file explorer.

First you need the correct permissions in you manifest file:
<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" />

I recommend to use a Application class at the beginning of you app.  That allows a proper file and log handling. Here is an example. That piece of code adds a new folder named  "MyPersonalAppFolder" with another folder called "log" in it to the public external storage. after that the logcat output is cleared and the new logcat output is written into a new file called logcatXXX.txt, where XXX is the are the milliseconds time at this moment.
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 + "/log" );
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 + " *:S MyActivity:D MyActivity2:D");
} 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;
}
}