Skip to content

Instantly share code, notes, and snippets.

@dGorod
Created October 19, 2017 15:01
Show Gist options
  • Save dGorod/8aaa04026af0b193796d10cf20ef57e4 to your computer and use it in GitHub Desktop.
Save dGorod/8aaa04026af0b193796d10cf20ef57e4 to your computer and use it in GitHub Desktop.
Example of new FileProvider usage
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
<paths>
<external-path name="Download" path="Download/" />
</paths>
private val downloadReceiver = object: BroadcastReceiver() {
val TAG = DownloadManager::class.java.simpleName
override fun onReceive(context: Context?, intent: Intent?) {
val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val downloadedId = intent!!.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L)
// read download session information
manager.query(DownloadManager.Query().setFilterById(downloadedId))?.let {
it.moveToFirst()
val status = it.getInt(it.getColumnIndex(DownloadManager.COLUMN_STATUS))
if (status == DownloadManager.STATUS_SUCCESSFUL) {
var path = it.getString(it.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
if (path.substring(0, 7).matches(Regex("file://"))) {
path = path.substring(7)
}
try {
val providerId = BuildConfig.APPLICATION_ID + ".provider"
val uri = FileProvider.getUriForFile(context, providerId, File(path))
openPdf(uri)
}
catch (ex: IllegalArgumentException) {
Logger.e(TAG, "Problems with FileProvider configuration.", ex)
}
}
else if (status == DownloadManager.STATUS_FAILED) {
toast(R.string.error_report_download)
val reason = it.getInt(it.getColumnIndex(DownloadManager.COLUMN_REASON))
Logger.w(TAG, "Download failed. Status: $status, reason: $reason")
}
}
}
}
private fun openPdf(uri: Uri) {
val openIntent = Intent(Intent.ACTION_VIEW)
openIntent.setDataAndType(uri, "application/pdf")
openIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
if (openIntent.isActionAvailable(this)) {
startActivity(openIntent)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment