Skip to content

Commit

Permalink
Merge pull request #287 from OxygenCobalt/main
Browse files Browse the repository at this point in the history
Improve/Optimize Coil Usage
  • Loading branch information
enricocid authored Apr 25, 2021
2 parents 48f0943 + 8e528db commit a30f411
Show file tree
Hide file tree
Showing 7 changed files with 112 additions and 236 deletions.
13 changes: 12 additions & 1 deletion project/app/src/main/java/com/iven/musicplayergo/GoApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ package com.iven.musicplayergo

import android.app.Application
import androidx.appcompat.app.AppCompatDelegate
import coil.ImageLoader
import coil.ImageLoaderFactory
import coil.request.CachePolicy
import com.iven.musicplayergo.helpers.ThemeHelper

val goPreferences: GoPreferences by lazy {
GoApp.prefs
}

class GoApp : Application() {
class GoApp : Application(), ImageLoaderFactory {

companion object {
lateinit var prefs: GoPreferences
Expand All @@ -19,4 +22,12 @@ class GoApp : Application() {
prefs = GoPreferences(applicationContext)
AppCompatDelegate.setDefaultNightMode(ThemeHelper.getDefaultNightMode(applicationContext))
}

override fun newImageLoader(): ImageLoader {
return ImageLoader.Builder(this)
.diskCachePolicy(CachePolicy.DISABLED)
.crossfade(true)
.error(R.drawable.album_art)
.build()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ import android.media.MediaExtractor
import android.media.MediaFormat
import android.net.Uri
import android.provider.MediaStore
import androidx.core.graphics.drawable.toBitmap
import androidx.core.net.toUri
import coil.Coil
import coil.request.ImageRequest
import com.iven.musicplayergo.R
import com.iven.musicplayergo.models.Music
import com.iven.musicplayergo.player.MediaPlayerHolder
Expand Down Expand Up @@ -70,27 +73,20 @@ fun Uri.toBitrate(context: Context): Pair<Int, Int>? {
}
}

fun Long.getCoverFromPFD(context: Context): Bitmap? {
val albumArtUri = ("content://media/external/audio/albumart").toUri()
val uri = ContentUris.withAppendedId(albumArtUri, this)
return try {
context.contentResolver.openFileDescriptor(uri, "r")?.let { pfd ->
val bitmap = BitmapFactory.decodeFileDescriptor(pfd.fileDescriptor)
pfd.close()
return bitmap
}
} catch (e: Exception) {
e.printStackTrace()
null
}
fun Long.toAlbumArtURI(): Uri {
return ContentUris.withAppendedId("content://media/external/audio/albumart".toUri(), this)
}

fun Long.getCoverFromURI(): Uri? = try {
val albumArtUri = ("content://media/external/audio/albumart").toUri()
ContentUris.withAppendedId(albumArtUri, this)
} catch (e: Exception) {
e.printStackTrace()
Uri.EMPTY
fun Long.waitForCover(context: Context, onDone: (Bitmap?) -> Unit) {
Coil.imageLoader(context).enqueue(
ImageRequest.Builder(context)
.data(toAlbumArtURI())
.target(
onSuccess = { onDone(it.toBitmap()) },
onError = { onDone(null) }
)
.build()
)
}

fun Long.toFormattedDuration(isAlbum: Boolean, isSeekBar: Boolean) = try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package com.iven.musicplayergo.fragments

import android.animation.Animator
import android.content.Context
import android.graphics.Bitmap
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
Expand All @@ -12,17 +11,14 @@ import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.widget.SearchView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.os.bundleOf
import androidx.core.text.parseAsHtml
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.ImageLoader
import coil.load
import coil.request.ImageRequest
import com.afollestad.recyclical.datasource.dataSourceOf
import com.afollestad.recyclical.setup
import com.afollestad.recyclical.withItem
Expand Down Expand Up @@ -91,23 +87,6 @@ class DetailsFragment : Fragment(R.layout.fragment_details), SearchView.OnQueryT

private var sPlayFirstSong = true

/**
* This is the job for all coroutines started by this ViewModel.
* Cancelling this job will cancel all coroutines started by this ViewModel.
*/
private val mLoadCoverJob = SupervisorJob()

private val mLoadCoverHandler = CoroutineExceptionHandler { _, exception ->
exception.printStackTrace()
}

private val mLoadCoverIoDispatcher = Dispatchers.IO + mLoadCoverJob + mLoadCoverHandler
private val mLoadCoverIoScope = CoroutineScope(mLoadCoverIoDispatcher)

private val sIsCovers get() = goPreferences.isCovers
private lateinit var mImageLoader: ImageLoader
private var mAlbumArt: Bitmap? = null

private var sOpenNewDetailsFragment = false

override fun onAttach(context: Context) {
Expand Down Expand Up @@ -147,13 +126,6 @@ class DetailsFragment : Fragment(R.layout.fragment_details), SearchView.OnQueryT
}
}

override fun onDestroy() {
super.onDestroy()
if (sIsCovers) {
mLoadCoverJob.cancel()
}
}

fun onHandleBackPressed(): Animator {
if (!mArtistDetailsAnimator.isRunning) {
_detailsFragmentBinding?.root?.run {
Expand Down Expand Up @@ -274,14 +246,6 @@ class DetailsFragment : Fragment(R.layout.fragment_details), SearchView.OnQueryT

private fun setupViews(view: View) {

if (sIsCovers && sLaunchedByArtistView || sIsCovers && sLaunchedByAlbumView) {
mImageLoader = ImageLoader.Builder(requireActivity())
.bitmapPoolingEnabled(false)
.crossfade(true)
.build()
mAlbumArt = ContextCompat.getDrawable(requireActivity(), R.drawable.album_art)?.toBitmap()
}

if (sLaunchedByArtistView) {

_detailsFragmentBinding?.albumViewCoverContainer?.handleViewVisibility(false)
Expand Down Expand Up @@ -701,7 +665,7 @@ class DetailsFragment : Fragment(R.layout.fragment_details), SearchView.OnQueryT
0
}

if (sIsCovers) {
if (goPreferences.isCovers) {
loadCoverIntoTarget(item.music?.get(0), albumCover)
}
}
Expand Down Expand Up @@ -757,23 +721,10 @@ class DetailsFragment : Fragment(R.layout.fragment_details), SearchView.OnQueryT
}

private fun loadCoverIntoTarget(song: Music?, target: ImageView) {
val request = ImageRequest.Builder(requireActivity())
.data(song?.albumId?.getCoverFromURI())
.target(
onSuccess = { result ->
// Handle the successful result.
target.load(result)
},
onError = {
target.load(mAlbumArt)
}
)
.build()

mLoadCoverIoScope.launch {
withContext(mLoadCoverIoDispatcher) {
mImageLoader.enqueue(request)
}
if (goPreferences.isCovers) {
target.load(song?.albumId?.toAlbumArtURI())
} else {
target.setImageResource(R.drawable.album_art)
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
package com.iven.musicplayergo.fragments

import android.content.Context
import android.graphics.Bitmap
import android.os.Bundle
import android.view.*
import androidx.appcompat.widget.SearchView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import coil.ImageLoader
import coil.load
import coil.request.ImageRequest
import com.afollestad.recyclical.datasource.emptyDataSource
import com.afollestad.recyclical.setup
import com.afollestad.recyclical.withItem
Expand Down Expand Up @@ -62,23 +58,6 @@ class MusicContainersListFragment : Fragment(R.layout.fragment_music_container_l
private var sIsFastScroller = false
private val sIsFastScrollerVisible get() = sIsFastScroller && mSorting != GoConstants.DEFAULT_SORTING

/**
* This is the job for all coroutines started by this ViewModel.
* Cancelling this job will cancel all coroutines started by this ViewModel.
*/
private val mLoadCoverJob = SupervisorJob()

private val mLoadCoverHandler = CoroutineExceptionHandler { _, exception ->
exception.printStackTrace()
}

private val mLoadCoverIoDispatcher = Dispatchers.IO + mLoadCoverJob + mLoadCoverHandler
private val mLoadCoverIoScope = CoroutineScope(mLoadCoverIoDispatcher)

private val sIsCovers get() = goPreferences.isCovers
private lateinit var mImageLoader: ImageLoader
private var mAlbumArt: Bitmap? = null

override fun onAttach(context: Context) {
super.onAttach(context)

Expand All @@ -95,13 +74,6 @@ class MusicContainersListFragment : Fragment(R.layout.fragment_music_container_l
}
}

override fun onDestroy() {
super.onDestroy()
if (sLaunchedByAlbumView && sIsCovers) {
mLoadCoverJob.cancel()
}
}

override fun onDestroyView() {
super.onDestroyView()
_musicContainerListBinding = null
Expand Down Expand Up @@ -132,15 +104,6 @@ class MusicContainersListFragment : Fragment(R.layout.fragment_music_container_l
}

private fun finishSetup() {

if (sLaunchedByAlbumView) {
mImageLoader = ImageLoader.Builder(requireActivity())
.bitmapPoolingEnabled(false)
.crossfade(true)
.build()
mAlbumArt = ContextCompat.getDrawable(requireActivity(), R.drawable.album_art)?.toBitmap()
}

_musicContainerListBinding?.artistsFoldersRv?.let { rv ->

// setup{} is an extension method on RecyclerView
Expand All @@ -153,27 +116,14 @@ class MusicContainersListFragment : Fragment(R.layout.fragment_music_container_l
withItem<String, ContainersAlbumViewHolder>(R.layout.containers_album_item) {
onBind(::ContainersAlbumViewHolder) { _, item ->
// ContainersAlbumViewHolder is `this` here
if (sIsCovers) {
val request = ImageRequest.Builder(requireActivity())
.data(mMusicViewModel.deviceMusicByAlbum?.get(item)?.get(0)?.albumId?.getCoverFromURI())
.target(
onSuccess = { result ->
// Handle the successful result.
albumCover.load(result)
},
onError = {
albumCover.load(mAlbumArt)
}
)
.build()

mLoadCoverIoScope.launch {
withContext(mLoadCoverIoDispatcher) {
mImageLoader.enqueue(request)
}
if (goPreferences.isCovers) {
val uri = mMusicViewModel.deviceMusicByAlbum?.get(item)?.get(0)?.albumId?.toAlbumArtURI()

albumCover.load(uri) {

}
} else {
albumCover.load(mAlbumArt)
albumCover.setImageResource(R.drawable.album_art)
}

title.text = item
Expand Down
Loading

0 comments on commit a30f411

Please sign in to comment.