how to play hardcoded content uri of local media file in exoplayer

Viewed 824

Initially I choose a Intent chooser to pick up a media file, and in onActivityResult i got the uri

fun openVideo(view: View) {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
        intent.type = "video/*"
        startActivityForResult(
            Intent.createChooser(intent, "Select video"),
            REQUEST_TAKE_GALLERY_VIDEO
        )
    }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
       ...
       ...     
            val selectedVideoUri: Uri? = data!!.data
            val vidPath: String = selectedVideoUri.toString()
            video_uri = Uri.parse(vidPath)

// the video uri looks like below      
//content://com.mi.android.globalFileexplorer.myprovider/external_files/Download/Dolittle%20(2020)%20%5B720p%5D%20%5BBluRay%5D%20%5BYTS.MX%5D/Dolittle.2020.720p.BluRay.x264.AAC-%5BYTS.MX%5D.mp4
            
           initializePlayer(video_uri)
       ...
       ...
        }
    }

Then I was able to playing the local file in exoplayer.

 fun initializePlayer(video_uri) {
        println("log initializePlayer called")
        player = ExoPlayerFactory.newSimpleInstance(this) // `player` was defined in GlobalVariables
        id_player_view.player = player

        if (video_uri != null) {
            println("log $video_uri ${video_uri!!::class.simpleName}")
            id_player_view.useController = true
            var mediaSource: MediaSource = buildMediaSource(video_uri!!)
            player?.playWhenReady = playWhenReady!!
            player?.seekTo(currentWindow!!, playBackPosition!!)
            player?.prepare(mediaSource, false, false)
        }
    }

But now, think that I saved the uri in database as a string. Then, assume I retrieved the content from database and pass it as a intent to video playing activity

now, if i write a code like this, and call initializePlayer the video is not playing.

video_uri = Uri.parse((intent.getStringExtra("video_url")))
println("log $video_uri ${video_uri!!::class.simpleName}")

initializePlayer(video_uri)

i.e for all hardcoded content uri of local media files. the exoplayer is not working.

How to solve this issue ?

1 Answers

think that I saved the uri in database as a string

You no longer have rights to access the content.

How to solve this issue ?

Use ACTION_OPEN_DOCUMENT to let the user choose the content. Then, in onActivityResult(), call takePersistableUriPermission() on a ContentResolver, to have access to that content for a longer period of time. See this blog post and the documentation for more.

Related