Tuesday, 1 June 2021

Android 11: Save a file that can other apps can access

(This question is regarding Android 11)

I want to print crash logs to a file that other applications can read (specifically, I want to be able to navigate to the file and view the data with the "Files" app).

I've seen dozens of answers to this question, but they all have one of two problems:

  1. they're using Environment.getExternalStoragePublicDirectory which is deprecated, or
  2. they're using getExternalFilesDir but this returns a directory that is not visible to other apps.

Please note I want to do this in my Application class, not in an activity.

According to the official docs I could save it as a "document", but the example provided there has a problem; it is invoked from an activity. Since I am trying to invoke it from an application, the method startActivityForResult doesn't exist.

// Request code for creating a PDF document.
const val CREATE_FILE = 1

private fun createFile(pickerInitialUri: Uri) {
    val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "application/pdf"
        putExtra(Intent.EXTRA_TITLE, "invoice.pdf")

        // Optionally, specify a URI for the directory that should be opened in
        // the system file picker before your app creates the document.
        putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri)
    }
    startActivityForResult(intent, CREATE_FILE) // <--- This does not compile, a subclass of Application doesn't have this method avaiable...
}


from Android 11: Save a file that can other apps can access

No comments:

Post a Comment