Skip to content

Commit 0e80bcf

Browse files
author
Leo Neat
committed
Switching to kotlin suspend funs
modified: mediacontroller/build.gradle modified: mediacontroller/src/main/java/com/example/android/mediacontroller/MediaAppControllerActivity.java modified: mediacontroller/src/main/java/com/example/android/mediacontroller/MediaBrowseTreeSnapshot.kt modified: mediacontroller/src/main/res/layout/media_browse_tree.xml modified: mediacontroller/build.gradle modified: mediacontroller/src/main/java/com/example/android/mediacontroller/MediaAppControllerActivity.java modified: mediacontroller/src/main/java/com/example/android/mediacontroller/MediaBrowseTreeSnapshot.kt modified: mediacontroller/src/main/res/layout/media_browse_tree.xml
1 parent 2c6fac8 commit 0e80bcf

File tree

4 files changed

+56
-90
lines changed

4 files changed

+56
-90
lines changed

mediacontroller/build.gradle

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,5 @@ dependencies {
4949
implementation "androidx.leanback:leanback:$leanback_version"
5050
implementation 'com.android.support:design:28.0.0'
5151
implementation "com.google.android.material:material:$material_version"
52+
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
5253
}

mediacontroller/src/main/java/com/example/android/mediacontroller/MediaAppControllerActivity.java

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,6 @@ public Object instantiateItem(@NonNull ViewGroup container, int position) {
260260
mBrowseMediaItemsAdapter.init(findViewById(R.id.media_browse_tree_top),
261261
findViewById(R.id.media_browse_tree_up), findViewById(R.id.media_browse_tree_save));
262262

263-
264263
final RecyclerView browseTreeListExtraSuggested = findViewById(R.id.media_items_list_extra_suggested);
265264
browseTreeListExtraSuggested.setLayoutManager(new LinearLayoutManager(this));
266265
browseTreeListExtraSuggested.setHasFixedSize(true);
@@ -846,8 +845,8 @@ private static class AudioFocusHelper
846845
private final Spinner mFocusTypeSpinner;
847846

848847
private AudioFocusHelper(@NonNull Context context,
849-
@NonNull ToggleButton focusToggleButton,
850-
@NonNull Spinner focusTypeSpinner) {
848+
@NonNull ToggleButton focusToggleButton,
849+
@NonNull Spinner focusTypeSpinner) {
851850

852851
mAudioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE);
853852
mToggleButton = focusToggleButton;
@@ -1137,7 +1136,6 @@ private class BrowseMediaItemsAdapter extends
11371136
private List<MediaBrowserCompat.MediaItem> mItems;
11381137
private final Stack<String> mNodes = new Stack<>();
11391138

1140-
11411139
MediaBrowserCompat.SubscriptionCallback callback =
11421140
new MediaBrowserCompat.SubscriptionCallback() {
11431141
@Override
@@ -1156,7 +1154,7 @@ public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
11561154
}
11571155

11581156
@Override
1159-
public void onBindViewHolder(@NonNull ViewHolder holder, int position){
1157+
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
11601158
if (mNodes.size() == 0) {
11611159
holder.name.setText(getString(R.string.media_no_browser));
11621160
holder.name.setVisibility(View.VISIBLE);
@@ -1184,6 +1182,7 @@ public void onBindViewHolder(@NonNull ViewHolder holder, int position){
11841182
});
11851183
return;
11861184
}
1185+
11871186
final MediaBrowserCompat.MediaItem item = mItems.get(position);
11881187
holder.name.setText(item.getDescription().getTitle());
11891188
holder.name.setVisibility(View.VISIBLE);
@@ -1272,21 +1271,24 @@ void init(View topButtonView, View upButtonView, View saveButtonView) {
12721271
private void takeMediaBrowseTreeSnapshot(){
12731272
if(mBrowser != null) {
12741273
if(mMediaBrowseTreeSnapshot == null) {
1275-
mMediaBrowseTreeSnapshot = new MediaBrowseTreeSnapshot(MediaAppControllerActivity.this, mBrowser);
1274+
mMediaBrowseTreeSnapshot = new MediaBrowseTreeSnapshot(
1275+
MediaAppControllerActivity.this, mBrowser);
12761276
}
12771277
Intent saveTextFileIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
12781278
saveTextFileIntent.addCategory(Intent.CATEGORY_OPENABLE);
12791279
saveTextFileIntent.setType("text/plain");
12801280
saveTextFileIntent.putExtra(
12811281
Intent.EXTRA_TITLE, DEFAULT_BROWSE_TREE_FILE_NAME);
1282-
MediaAppControllerActivity.this.startActivityForResult(saveTextFileIntent, CREATE_DOCUMENT_REQUEST_FOR_SNAPSHOT);
1282+
MediaAppControllerActivity.this.startActivityForResult(saveTextFileIntent,
1283+
CREATE_DOCUMENT_REQUEST_FOR_SNAPSHOT);
12831284

12841285
}else{
12851286
Log.e(TAG, "Media browser is null");
12861287
runOnUiThread(new Runnable() {
12871288
@Override
12881289
public void run() {
1289-
Toast.makeText(getApplicationContext(),"No media browser to snapshot", Toast.LENGTH_SHORT).show();
1290+
Toast.makeText(getApplicationContext(),"No media browser to snapshot",
1291+
Toast.LENGTH_SHORT).show();
12901292
}
12911293
});
12921294
}
@@ -1346,7 +1348,8 @@ private class SearchMediaItemsAdapter extends BrowseMediaItemsAdapter {
13461348
@Override
13471349
protected void subscribe() {
13481350
if (treeDepth() == 1) {
1349-
mBrowser.search(getCurrentNode(), null, new MediaBrowserCompat.SearchCallback() {
1351+
mBrowser.search(getCurrentNode(), null,
1352+
new MediaBrowserCompat.SearchCallback() {
13501353
@Override
13511354
public void onSearchResult(@NonNull String query, Bundle extras,
13521355
@NonNull List<MediaBrowserCompat.MediaItem> items) {
@@ -1373,4 +1376,4 @@ protected void unsubscribe() {
13731376
super.unsubscribe();
13741377
}
13751378
}
1376-
}
1379+
}

mediacontroller/src/main/java/com/example/android/mediacontroller/MediaBrowseTreeSnapshot.kt

Lines changed: 38 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -7,125 +7,85 @@ import android.support.v4.media.MediaBrowserCompat
77
import android.support.v4.media.MediaBrowserCompat.SubscriptionCallback
88
import android.util.Log
99
import android.widget.Toast
10+
import androidx.lifecycle.ViewModel
11+
import androidx.lifecycle.viewModelScope
12+
import kotlinx.coroutines.launch
1013
import java.io.OutputStream
1114
import java.io.PrintWriter
12-
import java.util.concurrent.ExecutorService
13-
import java.util.concurrent.Executors
14-
import java.util.concurrent.Semaphore
15+
import kotlin.coroutines.resume
16+
import kotlin.coroutines.suspendCoroutine
1517

1618

17-
class MediaBrowseTreeSnapshot(private val context: Context, private val browser: MediaBrowserCompat) {
19+
class MediaBrowseTreeSnapshot(private val context: Context, private val browser: MediaBrowserCompat):ViewModel() {
1820
private val TAG = "MediaBrowseTreeSnapshot"
1921

22+
2023
/**
2124
* Loads the browsers top level children and runs a DFS on them printing out
2225
* each media item's contentes as it is visited.
2326
*/
2427
fun takeBrowserSnapshot(outputStream: OutputStream) {
25-
val loaded = Semaphore(1)
26-
val executorService = Executors.newFixedThreadPool(4)
27-
val mItems: MutableList<MediaBrowserCompat.MediaItem> = ArrayList()
28-
executorService.execute {
29-
try {
30-
loaded.acquire()
31-
} catch (e: InterruptedException) {
32-
e.printStackTrace()
33-
}
34-
browser.subscribe(browser.root, object : SubscriptionCallback() {
35-
override fun onChildrenLoaded(parentId: String,
36-
children: List<MediaBrowserCompat.MediaItem>) {
37-
// Notify the main thread that all of the children have loaded
38-
Log.i(TAG, "Children loaded for init")
39-
mItems.addAll(children)
40-
loaded.release()
4128

42-
super.onChildrenLoaded(parentId, children)
29+
viewModelScope.launch {
30+
val mediaItems: MutableList<MediaBrowserCompat.MediaItem> = getChildNodes(browser.root)
31+
if (mediaItems.isNotEmpty()) {
32+
runDFSOnBrowseTree(mediaItems, outputStream)
33+
for (item in mediaItems) {
34+
Log.i(TAG, item.toString())
4335
}
44-
})
45-
46-
// Wait for all of the media children to be loaded before starting snapshot
47-
try {
48-
loaded.acquire()
49-
} catch (e: InterruptedException) {
50-
e.printStackTrace()
51-
}
52-
53-
if (mItems.size > 0) {
54-
runDFSOnBrowseTree(mItems, executorService, outputStream)
5536
} else {
5637
notifyUser("No media items found, could not save tree.")
5738
}
5839
}
5940
}
6041

42+
private suspend fun getChildNodes(rootItemMid: String): MutableList<MediaBrowserCompat.MediaItem> =
43+
suspendCoroutine {
44+
val mediaItems: MutableList<MediaBrowserCompat.MediaItem> = ArrayList()
45+
browser.subscribe(rootItemMid, object : SubscriptionCallback() {
46+
override fun onChildrenLoaded(parentId: String,
47+
children: List<MediaBrowserCompat.MediaItem>) {
48+
// Notify the main thread that all of the children have loaded
49+
mediaItems.addAll(children)
50+
super.onChildrenLoaded(parentId, children)
51+
it.resume(mediaItems)
52+
}
53+
})
54+
}
55+
6156
/**
6257
* Kicks off the browse tree depth first search by visiting all of the top level media
6358
* item nodes.
6459
*/
65-
private fun runDFSOnBrowseTree(mediaItems: MutableList<MediaBrowserCompat.MediaItem>, executorService: ExecutorService, outputStream: OutputStream) {
60+
private suspend fun runDFSOnBrowseTree(mediaItems: MutableList<MediaBrowserCompat.MediaItem>, outputStream: OutputStream) {
6661
val printWriter = PrintWriter(outputStream)
6762
printWriter.println("Root:")
68-
val writeCompleted = Semaphore(1)
69-
executorService.execute {
70-
for (item in mediaItems) {
71-
try {
72-
writeCompleted.acquire()
73-
} catch (e: InterruptedException) {
74-
e.printStackTrace()
75-
}
76-
visitMediaItemNode(item, printWriter, 1,
77-
executorService)
78-
writeCompleted.release()
79-
}
80-
printWriter.flush()
81-
printWriter.close()
82-
outputStream.close()
83-
notifyUser("MediaItems saved to specified location.")
63+
for (item in mediaItems) {
64+
visitMediaItemNode(item, printWriter, 1)
8465
}
66+
printWriter.flush()
67+
printWriter.close()
68+
outputStream.close()
69+
notifyUser("MediaItems saved to specified location.")
8570
}
8671

8772
/**
8873
* Visits a media item node by printing out its contents and then visiting all of its children.
8974
*/
90-
private fun visitMediaItemNode(mediaItem: MediaBrowserCompat.MediaItem?, printWriter: PrintWriter, depth: Int,
91-
executorService: ExecutorService) {
75+
private suspend fun visitMediaItemNode(mediaItem: MediaBrowserCompat.MediaItem?, printWriter: PrintWriter, depth: Int) {
9276
if (mediaItem != null) {
9377
printMediaItemDescription(printWriter, mediaItem, depth)
9478
val mid = if (mediaItem.mediaId != null) mediaItem.mediaId!! else ""
9579

9680
// If a media item is not a leaf continue DFS on it
9781
if (mediaItem.isBrowsable && mid != "") {
98-
val loaded = Semaphore(1)
99-
try {
100-
loaded.acquire()
101-
} catch (e: InterruptedException) {
102-
e.printStackTrace()
103-
}
104-
val mediaChildren: MutableList<MediaBrowserCompat.MediaItem> = ArrayList()
105-
executorService.execute {
106-
browser.subscribe(mid,
107-
object : SubscriptionCallback() {
108-
override fun onChildrenLoaded(parentId: String,
109-
children: List<MediaBrowserCompat.MediaItem>) {
110-
// Notify the main thread that all of the children have loaded
111-
mediaChildren.addAll(children)
112-
loaded.release()
113-
super.onChildrenLoaded(parentId, children)
114-
}
115-
})
116-
}
11782

118-
// Wait for all of the media children to be loaded before continuing DFS
119-
try {
120-
loaded.acquire()
121-
} catch (e: InterruptedException) {
122-
e.printStackTrace()
123-
}
83+
val mediaChildren: MutableList<MediaBrowserCompat.MediaItem> = getChildNodes(mid)
12484

12585
// Run visit on all of the nodes children
12686
for (mediaItemChild in mediaChildren) {
127-
visitMediaItemNode(mediaItemChild, printWriter, depth + 1,
128-
executorService)
87+
visitMediaItemNode(mediaItemChild, printWriter, depth + 1)
88+
Log.i(TAG, "Visiting:" + mediaItemChild.toString())
12989
}
13090
}
13191
}
@@ -147,7 +107,6 @@ class MediaBrowseTreeSnapshot(private val context: Context, private val browser:
147107
val infoStr = String.format(
148108
"%sTitle:%s,Subtitle:%s,MediaId:%s,URI:%s,Description:%s",
149109
tabStr, titleStr, subTitleStr, mIDStr, uriStr, desStr)
150-
Log.i(TAG, "Writing media Item");
151110
printWriter.println(infoStr)
152111
}
153112

mediacontroller/src/main/res/layout/media_browse_tree.xml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,10 @@
4444
android:layout_height="wrap_content"
4545
android:text="@string/media_browse_tree_up" />
4646

47-
<Button android:id="@+id/media_browse_tree_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/media_browse_tree_save"/>
47+
<Button android:id="@+id/media_browse_tree_save"
48+
android:layout_width="wrap_content"
49+
android:layout_height="wrap_content"
50+
android:text="@string/media_browse_tree_save"/>
4851

4952
LinearLayout>
5053

0 commit comments

Comments
 (0)