thahgr
thahgr

Reputation: 795

Android "open with" implementation

I am trying to open downloaded files in an Android app with Kotlin. For the moment I can open with the recommended app on the system by setting the type of the file with the below code

class Somelistener(private val workManager: WorkManager, private val adapter: someAdapter, private val lifecycle: LifecycleOwner) : AdapterView.OnItemClickListener {


private fun openWithOther(path: String?, context: Context?) {
    if (path == null || context == null) {
        return
    }
    val uri: Uri = Uri.fromFile(File(path))
    val mime: String? = getMimeType(path)

    val intent = Intent()
    intent.action = Intent.ACTION_VIEW
    intent.setDataAndType(uri, mime)
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    startActivity(context, intent, null)
}

However, we need to not open directly the file but ask the user with a "open with" prompt where the user can tryout which app he wants to open it with.

Can this be done ? With what kind of intent ?

Secondary questions, not necessary for answer, at the startActivity with intent, the bundle should be null as i have it ? Also I cant seem to find some startActivity for result.

Upvotes: 0

Views: 1026

Answers (1)

P.Juni
P.Juni

Reputation: 2485

What u are looking for is App chooser. U can create it via Intent.createChooser(target, title). In your scenario it would be:

with(Intent(Intent.ACTION_VIEW)) {
    setDataAndType(uri, mime)
    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    val chooserIntent = Intent.createChooser(this, null)
    activity?.startActivity(chooserIntent)
}

See App Chooser

Upvotes: 2

Related Questions