Skip to content

Commit

Permalink
Reverted the delay load fragment load (not possible) and bit more cod…
Browse files Browse the repository at this point in the history
…e cleanup
  • Loading branch information
izderadicka committed May 6, 2018
1 parent c65487f commit 18f44d2
Show file tree
Hide file tree
Showing 11 changed files with 121 additions and 104 deletions.
16 changes: 8 additions & 8 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,18 @@ android {

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:support-v4:27.0.2'
implementation 'com.android.support:design:27.0.2'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.google.android.exoplayer:exoplayer-core:2.7.0'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.7.0'
implementation 'com.google.android.exoplayer:extension-mediasession:2.7.0'
implementation 'com.android.volley:volley:1.1.0'
implementation 'ru.noties:markwon:1.0.4'
testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-core:2.+'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
testImplementation 'org.mockito:mockito-core:2.18.3'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
90 changes: 52 additions & 38 deletions app/src/main/java/eu/zderadicka/audioserve/AudioService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.net.Uri
import android.os.*
Expand All @@ -28,7 +29,6 @@ import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector
import com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator
import com.google.android.exoplayer2.source.DynamicConcatenatingMediaSource
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import eu.zderadicka.audioserve.data.*
import eu.zderadicka.audioserve.net.ApiClient
Expand Down Expand Up @@ -133,8 +133,17 @@ class AudioService : MediaBrowserServiceCompat() {
}
}

private var audioRequest: AudioFocusRequest? = null

fun requestAudioFocus(): Boolean {
val result = am.requestAudioFocus(focusCallback, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
val result = if (Build.VERSION.SDK_INT >= 26) {
audioRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setOnAudioFocusChangeListener(focusCallback).build()
am.requestAudioFocus(audioRequest)
} else {
@Suppress("DEPRECATION")
am.requestAudioFocus(focusCallback, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
}
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
}

Expand All @@ -152,7 +161,12 @@ class AudioService : MediaBrowserServiceCompat() {
super.onStop(player)
session.isActive = false
stopMe()
am.abandonAudioFocus(focusCallback)
if (Build.VERSION.SDK_INT >= 26) {
audioRequest?.let { am.abandonAudioFocusRequest(it) }
} else {
@Suppress("DEPRECATION")
am.abandonAudioFocus(focusCallback)
}
}
}

Expand Down Expand Up @@ -214,7 +228,7 @@ class AudioService : MediaBrowserServiceCompat() {
deletePreviousQueueItem = -1
if (folderPosition >= 0 && sourceFactory!=null) {
val factory = sourceFactory?: throw IllegalStateException("Session not ready")
var source: MediaSource

playQueue = currentFolder.slice(folderPosition until currentFolder.size).toMutableList()
cacheManager.resetLoading(* playQueue.slice(0 until min(preloadFiles+1, playQueue.size))
.map{it.mediaId!!}.toTypedArray())
Expand All @@ -223,7 +237,7 @@ class AudioService : MediaBrowserServiceCompat() {
val transcode = cacheManager.shouldTranscode(it)
factory.createMediaSource(apiClient.uriFromMediaId(it.mediaId!!, transcode))
}
source = DynamicConcatenatingMediaSource()
val source = DynamicConcatenatingMediaSource()
source.addMediaSources(ms)
currentSourcesList =source

Expand Down Expand Up @@ -425,23 +439,21 @@ class AudioService : MediaBrowserServiceCompat() {
}
}

private val prefsListener = object : SharedPreferences.OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String?) {
when (key) {
"pref_server_url", "pref_shared_secret" -> apiClient.loadPreferences()
"pref_preload" -> {
preloadFiles = sharedPreferences.getString("pref_preload","2").toInt()
}
"pref_cache_location" -> {
preparer.sourceFactory = null
}
"pref_offline" -> {
isOffline = sharedPreferences.getBoolean("pref_offline", false)
preparer.sourceFactory = null
}
private val prefsListener = SharedPreferences.OnSharedPreferenceChangeListener {
sharedPreferences, key ->
when (key) {
"pref_server_url", "pref_shared_secret" -> apiClient.loadPreferences()
"pref_preload" -> {
preloadFiles = sharedPreferences.getString("pref_preload","2").toInt()
}
"pref_cache_location" -> {
preparer.sourceFactory = null
}
"pref_offline" -> {
isOffline = sharedPreferences.getBoolean("pref_offline", false)
preparer.sourceFactory = null
}
}

}

private lateinit var queueManager: QueueManager
Expand Down Expand Up @@ -499,7 +511,7 @@ mediaSessionConnector.setErrorMessageProvider(messageProvider);


var isStartedInForeground = false
var isStarted = false
private var isStarted = false

fun startMe(notification: Notification) {

Expand Down Expand Up @@ -645,20 +657,22 @@ mediaSessionConnector.setErrorMessageProvider(messageProvider);
}

private fun onLoadChildrenOffline(parentId: String, result: Result<List<MediaItem>>, options: Bundle) {
if (parentId == EMPTY_ROOT_TAG) {
result.sendResult(ArrayList())
} else if (parentId == MEDIA_ROOT_TAG) {
Log.d(LOG_TAG, "Requesting offline root")
result.sendResult(cacheManager.cacheBrowser.rootFolder)
} else {
result.detach()
val t = Thread({
val res = cacheManager.cacheBrowser.listFolder(parentId)
currentFolder = res.filter{it.isPlayable}
result.sendResult(res)
prepareLatestItem(folderIdFromOfflinePath(parentId), options)
}, "Retrieve folder")
t.start()
when (parentId) {
EMPTY_ROOT_TAG -> result.sendResult(ArrayList())
MEDIA_ROOT_TAG -> {
Log.d(LOG_TAG, "Requesting offline root")
result.sendResult(cacheManager.cacheBrowser.rootFolder)
}
else -> {
result.detach()
val t = Thread({
val res = cacheManager.cacheBrowser.listFolder(parentId)
currentFolder = res.filter{it.isPlayable}
result.sendResult(res)
prepareLatestItem(folderIdFromOfflinePath(parentId), options)
}, "Retrieve folder")
t.start()
}
}
}

Expand Down Expand Up @@ -782,10 +796,10 @@ mediaSessionConnector.setErrorMessageProvider(messageProvider);
override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): MediaBrowserServiceCompat.BrowserRoot? {
Log.d(LOG_TAG, "Requesting root mediaId")
// TODO For now allow browser access from same application - latter consider Package manager from Universal player
if (Process.SYSTEM_UID == clientUid || Process.myUid() == clientUid) {
return BrowserRoot(MEDIA_ROOT_TAG, null)
return if (Process.SYSTEM_UID == clientUid || Process.myUid() == clientUid) {
BrowserRoot(MEDIA_ROOT_TAG, null)
} else {
return BrowserRoot(EMPTY_ROOT_TAG, null)
BrowserRoot(EMPTY_ROOT_TAG, null)
}
}

Expand Down
45 changes: 24 additions & 21 deletions app/src/main/java/eu/zderadicka/audioserve/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package eu.zderadicka.audioserve

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
Expand Down Expand Up @@ -58,13 +59,13 @@ class MainActivity : AppCompatActivity(),
private lateinit var mBrowser: MediaBrowserCompat
private lateinit var controllerFragment: ControllerFragment
private var pendingMediaItem: MediaBrowserCompat.MediaItem? = null
private var search_prefix: String? = null
private var searchPrefix: String? = null
private var folderDetails: Bundle? = null

private val mediaServiceConnectionCallback = object : MediaBrowserCompat.ConnectionCallback() {
override fun onConnected() {
super.onConnected()
val token = mBrowser.getSessionToken()
val token = mBrowser.sessionToken
val mediaController = MediaControllerCompat(this@MainActivity, // Context
token)
MediaControllerCompat.setMediaController(this@MainActivity, mediaController)
Expand Down Expand Up @@ -166,7 +167,7 @@ class MainActivity : AppCompatActivity(),
}

val collection: Int? = collectionFromFolderId(folderId)
search_prefix = if (collection == null || isOffline) null else "${AudioService.SEARCH_PREFIX}${collection}_"
searchPrefix = if (collection == null || isOffline) null else "${AudioService.SEARCH_PREFIX}${collection}_"
this.folderDetails = folderDetails
invalidateOptionsMenu()
}
Expand All @@ -183,6 +184,7 @@ class MainActivity : AppCompatActivity(),

private lateinit var drawerToggle: ActionBarDrawerToggle

@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Expand Down Expand Up @@ -217,8 +219,8 @@ class MainActivity : AppCompatActivity(),
navHeader.findViewById<TextView>(R.id.homeLinkView).movementMethod = LinkMovementMethod()

try {
val pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
val version = pInfo?.versionName;
val pInfo = this.packageManager.getPackageInfo(packageName, 0)
val version = pInfo?.versionName
val nameView = navHeader.findViewById<TextView>(R.id.appNameView)
nameView.text = "audioserve v. $version"
} catch (e: PackageManager.NameNotFoundException) {
Expand All @@ -231,7 +233,7 @@ class MainActivity : AppCompatActivity(),
val itemId = intent.getStringExtra(METADATA_KEY_MEDIA_ID)
val folderId = folderIdFromFileId(itemId)
val name = File(folderId).name
openInitalFolder(folderId, name)
openInitialFolder(folderId, name)
rootFolder = ROOT_RECENT

} else {
Expand All @@ -248,8 +250,8 @@ class MainActivity : AppCompatActivity(),
createOfflineSwitch()

val prefs = PreferenceManager.getDefaultSharedPreferences(this)
val haveServer = prefs.getString("pref_server_url", "").length>0
val haveSecret = prefs.getString(("pref_shared_secret"), "").length>0
val haveServer = prefs.getString("pref_server_url", "").isNotEmpty()
val haveSecret = prefs.getString(("pref_shared_secret"), "").isNotEmpty()

if (!haveSecret || !haveServer) startActivity(Intent(this, SettingsActivity::class.java))

Expand All @@ -260,9 +262,9 @@ class MainActivity : AppCompatActivity(),

private fun createOfflineSwitch() {
// test switch
val actionView = nav_view.menu.findItem(R.id.offline_switch).getActionView()
val actionView = nav_view.menu.findItem(R.id.offline_switch).actionView
val switcher = actionView.findViewById(R.id.switcher) as SwitchCompat
switcher.isChecked = isOffline;
switcher.isChecked = isOffline
switcher.setOnClickListener{
val makeOffline = switcher.isChecked
val editor = PreferenceManager.getDefaultSharedPreferences(this@MainActivity).edit()
Expand All @@ -281,21 +283,21 @@ class MainActivity : AppCompatActivity(),

private fun openRootFolder() {
stopPlayback()
openInitalFolder(AudioService.MEDIA_ROOT_TAG,
openInitialFolder(AudioService.MEDIA_ROOT_TAG,
if (isOffline) getString(R.string.collection_offline)
else getString(R.string.collections_title))
rootFolder = ROOT_BROWSE
}

private fun openRecentFolder() {
stopPlayback()
openInitalFolder(AudioService.RECENTLY_LISTENED_TAG, getString(R.string.recently_listened))
openInitialFolder(AudioService.RECENTLY_LISTENED_TAG, getString(R.string.recently_listened))
rootFolder = ROOT_RECENT
}


private fun showUpNavigation() {
drawerToggle.isDrawerIndicatorEnabled = supportFragmentManager.getBackStackEntryCount() < 1
drawerToggle.isDrawerIndicatorEnabled = supportFragmentManager.backStackEntryCount < 1


}
Expand All @@ -315,7 +317,7 @@ class MainActivity : AppCompatActivity(),
val folderId = folderIdFromFileId(mediaId)
if (folderId != folderFragment?.folderId) {
val name = File(folderId).name
openInitalFolder(folderId, name)
openInitialFolder(folderId, name)
}
}
}
Expand Down Expand Up @@ -345,6 +347,7 @@ class MainActivity : AppCompatActivity(),
private var svc: SleepService? = null
override fun onServiceDisconnected(name: ComponentName?) {
svc?.statusListener = null
svc = null
}

override fun onServiceConnected(name: ComponentName?, service: IBinder) {
Expand Down Expand Up @@ -400,7 +403,7 @@ class MainActivity : AppCompatActivity(),

menuInflater.inflate(R.menu.main, menu)
val searchItem = menu.findItem(R.id.action_search)
searchItem.isVisible = search_prefix != null
searchItem.isVisible = searchPrefix != null
val infoItem = menu.findItem(R.id.action_info)
infoItem.isVisible = folderDetails != null
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
Expand All @@ -415,7 +418,7 @@ class MainActivity : AppCompatActivity(),
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
Log.d(LOG_TAG, "Clicked menu item id ${item.itemId} which is resource ${getResources().getResourceName(item.itemId)}")
Log.d(LOG_TAG, "Clicked menu item id ${item.itemId} which is resource ${resources.getResourceName(item.itemId)}")
when (item.itemId) {
R.id.action_reload -> {
folderFragment?.reload()
Expand All @@ -436,7 +439,7 @@ class MainActivity : AppCompatActivity(),
}
}

private fun openInitalFolder(folderId: String, folderName: String) {
private fun openInitialFolder(folderId: String, folderName: String) {
//
for (i in 0..supportFragmentManager.backStackEntryCount) {
supportFragmentManager.popBackStack()
Expand Down Expand Up @@ -504,13 +507,13 @@ class MainActivity : AppCompatActivity(),

override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
Log.d(LOG_TAG, "New intent arrived with action ${intent?.action}")
Log.d(LOG_TAG, "New intent arrived with action ${intent.action}")

if (Intent.ACTION_SEARCH == intent.getAction() && search_prefix != null) {
if (Intent.ACTION_SEARCH == intent.action && searchPrefix != null) {
val query = intent.getStringExtra(SearchManager.QUERY)
if (query != null && query.length > 3) {
val searchId = search_prefix + query
Log.d(LOG_TAG, "Seaching for $query")
val searchId = searchPrefix + query
Log.d(LOG_TAG, "Searching for $query")
newFolderFragment(searchId, query, true)
} else {
Toast.makeText(this, getString(R.string.search_warning), Toast.LENGTH_LONG).show()
Expand Down
Loading

0 comments on commit 18f44d2

Please sign in to comment.