Skip to content

Instantly share code, notes, and snippets.

@Phocacius
Created November 28, 2017 14:17
Show Gist options
  • Save Phocacius/5a3fefee934bfe9716b01a83382e6427 to your computer and use it in GitHub Desktop.
Save Phocacius/5a3fefee934bfe9716b01a83382e6427 to your computer and use it in GitHub Desktop.
Custom ContentProvider for Android to enable files stored in the internal storage to be opened by external apps
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import java.io.File
import java.io.FileNotFoundException
/**
* Created by thorstenhack on 28.11.17.
* Declare in manifest: <provider android:name=".FileProvider" android:authorities="com.your.package" android:exported="true" />
* Usage:
* val intent = Intent().setDataAndType(Uri.parse("content://com.your.package/${relativePathInFilesDir}", "mimetype")
* intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
* startActivity(intent)
*/
class FileProvider : ContentProvider() {
override fun insert(uri: Uri?, values: ContentValues?): Uri? = null
override fun query(uri: Uri?, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
override fun onCreate() = true
override fun update(uri: Uri?, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?) = 0
override fun delete(uri: Uri?, selection: String?, selectionArgs: Array<out String>?) = 0
override fun getType(uri: Uri?) = null
@Throws(FileNotFoundException::class)
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
val privateFile = File(context!!.filesDir, uri.path)
return ParcelFileDescriptor.open(privateFile, ParcelFileDescriptor.MODE_READ_ONLY)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment