Сбор элементов мультимедиа с помощью MediaBrowserCompat.Mediaitem
Мой текущий подход к получению всех файлов Musik - это Resolver и Cursor. Теперь я прочитал, есть лучшие методы. Я пытался использовать MediaBrowserCompat.MediaItem
но, видимо, я не получаю должного вывода? Мой onLoadChildren
функционирует просто неправильно или я называю это неправильно в основной активности?
Основная деятельность:
package com.name.mediabrowsertest
import android.content.ComponentName
import android.content.Context
import android.content.res.Configuration
import android.media.AudioManager
import android.media.session.MediaController
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.support.annotation.RequiresApi
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
import android.view.View
import android.widget.ImageView
class MainActivity : AppCompatActivity() {
private lateinit var mMediaBrowser: MediaBrowserCompat
fun buildTransportControls(){
var mMediaItems = mMediaBrowser.subscribe(mMediaBrowser.root,object: MediaBrowserCompat.SubscriptionCallback(){})
var mPlayPause = findViewById<ImageView>(R.id.imageView)
//Attach listen to button
mPlayPause.setOnClickListener(object: View.OnClickListener {
override fun onClick(v : View ){
var pbSate = MediaControllerCompat.getMediaController(this@MainActivity).playbackState.playbackState
if(pbSate == PlaybackStateCompat.STATE_PLAYING){
MediaControllerCompat.getMediaController(this@MainActivity).transportControls.pause()
}else{
var test = MediaBrowserCompat.MediaItem.CONTENTS_FILE_DESCRIPTOR
Log.i("TEST",test.toString())
MediaControllerCompat.getMediaController(this@MainActivity).transportControls.playFromMediaId(MediaBrowserCompat.EXTRA_MEDIA_ID,null)
MediaControllerCompat.getMediaController(this@MainActivity).transportControls.play()
//MediaControllerCompat.getMediaController(this@MainActivity).transportControls.playFromMediaId()
Log.i("TEST","TEST")
}
}
})
var mediaController = MediaControllerCompat.getMediaController(this@MainActivity)
//Show Init state
var metadat = mediaController.metadata
var pbState = mediaController.playbackState
//Register Callback to stay synced
mediaController.registerCallback(controllerCallback)
}
val controllerCallback = object : MediaControllerCompat.Callback() {
override fun onMetadataChanged(metadat:MediaMetadataCompat){
Log.i("Musik",metadat.toString())
}
override fun onPlaybackStateChanged(state :PlaybackStateCompat){}
}
private val mConnectionCallbacks = object : MediaBrowserCompat.ConnectionCallback() {
override fun onConnected() {
Log.i("Connection","Connecting")
// Get the token for the MediaSession
val token = mMediaBrowser.sessionToken
// Create a MediaControllerCompat
val mediaController = MediaControllerCompat(this@MainActivity,token)
// Save the controller
MediaControllerCompat.setMediaController(this@MainActivity, mediaController)
// Finish building the UI
buildTransportControls()
}
override fun onConnectionSuspended() {
// The Service has crashed. Disable transport controls until it automatically reconnects
Log.i("ERROR","Connection Suspended")
}
override fun onConnectionFailed() {
// The Service has refused our connection
Log.i("ERROR","Connection Failed")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.i("Hello World","Hello")
//Create MediaBrowser Service
mMediaBrowser = MediaBrowserCompat(this,
ComponentName(this, MediaPlaybackService::class.java),
mConnectionCallbacks,
null)
Log.i("Hello World","Hello2")
}
override fun onStart() {
super.onStart()
mMediaBrowser.connect()
}
override fun onResume() {
super.onResume()
volumeControlStream = AudioManager.STREAM_MUSIC
}
override fun onStop() {
super.onStop()
if(MediaControllerCompat.getMediaController(this@MainActivity) != null){
MediaControllerCompat.getMediaController(this@MainActivity).unregisterCallback(controllerCallback)
}
mMediaBrowser.disconnect()
}
}
Обслуживание:
package com.name.mediabrowsertest
import android.media.MediaDescription
import android.media.browse.MediaBrowser
import android.media.session.MediaSession
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaBrowserServiceCompat
import android.support.v4.media.MediaDescriptionCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
class MediaPlaybackService: MediaBrowserServiceCompat(){
private val MY_MEDIA_ROOT_ID = "MediaStore.Audio.Media.EXTERNAL_CONTENT_URI"
private lateinit var mMediaSession: MediaSessionCompat
private lateinit var mStateBuilder : PlaybackStateCompat.Builder
private var MySessionCallback =object : MediaSessionCompat.Callback() {
override fun onPause() {
super.onPause()
}
override fun onPlay() {
super.onPlay()
}
}
override fun onCreate() {
super.onCreate()
//Create the MediaSession
mMediaSession = MediaSessionCompat(this,"PLAYER")
//Setting the necessary Flags (Media Buttons)
mMediaSession.setFlags(
MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS)
//Set an inital PlaybackStatewith ACTION_BUTTONS, so Media buttons can start the player
mStateBuilder = PlaybackStateCompat.Builder().setActions(
PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE)
//Set our PLaybackState for the MediaSession
mMediaSession.setPlaybackState(mStateBuilder.build())
//Handles callbacks from Media Controller MySessionCalback is a PlaeHolder
mMediaSession.setCallback(MySessionCallback)
//Set SessionToken so Activites can communicate with it
sessionToken = mMediaSession.sessionToken
}
override fun onLoadChildren(parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) {
var mediaItems:ArrayList<MediaBrowserCompat.MediaItem> = ArrayList()
var builder = MediaDescriptionCompat.Builder()
builder.setDescription("T")
builder.setTitle("Media Items")
var mediaItem = MediaBrowserCompat.MediaItem(builder.build(),MediaBrowser.MediaItem.FLAG_PLAYABLE)
mediaItems.add(mediaItem)
var res = mediaItems.toMutableList()
for(x in res){
Log.i("Musik",x.toString())
}
result.sendResult(res)
}
override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot? {
return BrowserRoot(MY_MEDIA_ROOT_ID,null)
}
}