Skip to content

Instantly share code, notes, and snippets.

@mo7amd89
Created January 3, 2023 11:03
Show Gist options
  • Save mo7amd89/c5ce8b9d52c0f82cc9cbdc8d36f1154e to your computer and use it in GitHub Desktop.
Save mo7amd89/c5ce8b9d52c0f82cc9cbdc8d36f1154e to your computer and use it in GitHub Desktop.
Saving Logcat to a text file in Android Device
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment