ACTION_VIEW intent for a file with unknown MimeType

后端 未结 13 1801
抹茶落季
抹茶落季 2020-11-27 10:57

My app has a feature that browse files on your phone and SD card and open them using other apps. I want a solution where I don\'t have to specify the MimeType and can work w

13条回答
  •  执笔经年
    2020-11-27 11:36

    I wrote these few lines in kotlin and and it works like a charm.Enjoy it.

    val file = File(path)              
    val mimeType = URLConnection.guessContentTypeFromName(file.absolutePath)
                    Intent().apply {
                        setDataAndType(Uri.fromFile(file), mimeType)
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    }.let {
                        try {
                            itemView.context.startActivity(it)
                        } catch (e: ActivityNotFoundException) {
                            Toast.makeText(itemView.context, "There's no program to open this file", Toast.LENGTH_LONG).show()
                        }
                    }
    

提交回复
热议问题