Skip to content

Instantly share code, notes, and snippets.

@Rohit-554
Created July 7, 2023 11:21
Show Gist options
  • Select an option

  • Save Rohit-554/813f5a444faec9ce7bc6bf7f84fb0a2a to your computer and use it in GitHub Desktop.

Select an option

Save Rohit-554/813f5a444faec9ce7bc6bf7f84fb0a2a to your computer and use it in GitHub Desktop.
SearchPdfFilesWithPermisson
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
checkPermission()
displayPdfFiles(this)
}
fun displayPdfFiles(context: Context) {
//count time
val pdfFiles = mutableListOf<String>()
val selection = MediaStore.Files.FileColumns.MIME_TYPE + "=?"
val selectionArgs = arrayOf("application/pdf")
val uri = MediaStore.Files.getContentUri("external")
val projection = arrayOf(
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.TITLE,
MediaStore.Files.FileColumns.SIZE,
MediaStore.Files.FileColumns.DATE_ADDED
)
val sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC"
context.contentResolver.query(uri, projection, selection, selectionArgs, sortOrder)
?.use { cursor ->
Log.d("checkpdffiles", "Found ${cursor.count} PDF files")
val endtime = System.currentTimeMillis()
val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID)
val titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE)
while (cursor.moveToNext()) {
val id = cursor.getLong(idColumn)
val title = cursor.getString(titleColumn)
val contentUri = ContentUris.withAppendedId(uri, id)
Log.d("checkpdffiles", "Found PDF file: $title $contentUri")
pdfFiles.add(title)
}
}
}
private fun checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (!Environment.isExternalStorageManager()) {
val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
intent.addCategory("android.intent.category.DEFAULT")
intent.data = Uri.parse(String.format("package:%s", this.packageName))
startActivity(intent, Bundle.EMPTY)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment