Skip to content

Instantly share code, notes, and snippets.

@happysingh23828
Last active September 23, 2022 05:06
Show Gist options
  • Save happysingh23828/2229dc8fbb745f27dd0725fa91948d19 to your computer and use it in GitHub Desktop.
Save happysingh23828/2229dc8fbb745f27dd0725fa91948d19 to your computer and use it in GitHub Desktop.
Add logs to .txt file for Android.
<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/filepaths"
tools:replace="android:resource" />
</provider>
<cache-path
name="text_logs"
path="TextLogs"/>
package com.example.utils
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.content.FileProvider
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
object HappyTextLogger {
private var logStringBuilder: StringBuffer = StringBuffer()
private var fileName: String? = null
fun log(text: String) {
logStringBuilder.appendLine("${getCurrentDateTime()} ===> $text")
Log.d("Text-Log", text)
}
fun reset(context: Context) {
logStringBuilder = StringBuffer()
this.fileName?.let { nameToDelete ->
runCatching {
File(context.cacheDir, nameToDelete).delete()
}
}
}
private fun getCurrentDateTime(): String {
return SimpleDateFormat(
"dd-MM-yyyy-hh:mm:ss a",
Locale.getDefault()
).format(Calendar.getInstance().time)
}
fun shareTextFile(context: Context) {
this.fileName = "Text-Log-${getCurrentDateTime()}.txt"
runCatching {
val logsFolder = File(context.cacheDir, "TextLogs")
if (logsFolder.exists().not()) {
logsFolder.mkdir()
}
val file = File(logsFolder, fileName!!)
file.writeText(logStringBuilder.toString())
val authority = "${context.packageName}.provider"
val uri = FileProvider.getUriForFile(context, authority, file)
val sharingIntent = Intent(Intent.ACTION_SEND)
sharingIntent.type = "text/*"
sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri)
context.startActivity(Intent.createChooser(sharingIntent, "share file with"))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment