Skip to content

Instantly share code, notes, and snippets.

@danielgomezrico
Created January 18, 2017 16:56
Show Gist options
  • Save danielgomezrico/7e106549bd74d0f6c4cf45f3f8a246ed to your computer and use it in GitHub Desktop.
Save danielgomezrico/7e106549bd74d0f6c4cf45f3f8a246ed to your computer and use it in GitHub Desktop.
Android - how to get logcat File
class AndroidDevice(val activity: AppCompatActivity) {
/**
* Source: http://stackoverflow.com/a/22174245/273119
*/
fun readLogFile(): String {
val fullName = "appLog.log"
val file = File(activity.cacheDir, fullName)
val pid = android.os.Process.myPid().toString()
if (file.exists()) {
file.delete()
}
try {
val command = String.format("logcat -d -v threadtime *:*")
val process = Runtime.getRuntime().exec(command)
val reader = BufferedReader(InputStreamReader(process.inputStream))
val result = StringBuilder()
var currentLine = reader.readLine()
while (currentLine != null) {
currentLine = reader.readLine()
if (currentLine != null && currentLine.contains(pid)) {
result.append(currentLine).append("\n")
}
}
val out = FileWriter(file)
out.write(result.toString())
out.close()
} catch (e: IOException) {
Toast.makeText(activity, e.toString(), Toast.LENGTH_SHORT).show()
}
try {
Runtime.getRuntime().exec("logcat -c")
} catch (e: IOException) {
Toast.makeText(activity, e.toString(), Toast.LENGTH_SHORT).show()
}
return file.path
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment