MediaBrowserCompat queue find item

As per Uamp sample when onPlayFromMediaId is called its mediaId is matched with list of queueitems already stored using iterator as below

public static int getMusicIndexOnQueue(Iterable<MediaSessionCompat.QueueItem> queue,
         String mediaId) {
    int index = 0;
    for (MediaSessionCompat.QueueItem item : queue) {
        if (mediaId.equals(item.getDescription().getMediaId())) {
            return index;
        }
        index++;
    }
    return -1;
} 

this works great unless you have some thousand items in your list, its lags badly, is there any way I can get the index on queue in this scenario?

P.S.- This code is from v1 branch although v2 kotlin based branch has the same concept.

728x90

1 Answers MediaBrowserCompat queue find item

There is no API available that gets you this directly. So, you have to build your own data structure.

I created a HashMap of MediaId's as key and Index as its value. This will help you fetch the QueueItem faster. The question then becomes, when to create this HashMap. I created this in the callback when you are fetching the media List (QueueItem) from the device. The idea is to create this Map in background.

HashMap<String, Integer> mediaIndexMap = new HashMap<String, Integer>();
int index = 0;
for (MediaSessionCompat.QueueItem item : queue) {
    mediaIndexMap.put(item.getDescription().getMediaId(), index++);
}

Hopefully this preprocessing QueuItem should work for constant time lookup/fetch.

1 weeks ago