Shahraiz T.
Shahraiz T.

Reputation: 338

Scan for beacons and reorder list based on distance

My Android application uses the AltBeacon library implemented in a singleton class that scans beacons in a predefined region and stores them as a static list. In one of the activities of my app, I have a list of all items linked to beacons and I basically want this list to keep on reordering itself based on which beacon is closest. How can I do this seeing that I'm already using a comparator implementation and achieving this but I want to use something more sensible performance-wise, such as listeners.

Right now, I'm doing the following:

  1. Scan for beacons every x seconds and get the results as a Collection
  2. Store them in a new list
  3. Sort this list based on distance using Collections.sort
  4. Iterate over this list and send each beacon's id to the server to fetch more content linked to it.
  5. Once iteration is complete, I notify the RecyclerView adapter
  6. By this time, it is already time to do step 1 again.

Upvotes: 0

Views: 141

Answers (1)

davidgyoung
davidgyoung

Reputation: 64916

There is nothing really wrong with sorting the list each time. The typical alternative to resorting it for each scan cycle would be to insert/update the records into a collection that automatically maintains sort order. But since beacons in range will keep changing their estimated distance slightly for each scan cycle, the code would effectively be doing a full re-sort each time anyway. Bottom line: the way you are currently doing the sort is probably OK.

That said, item 4 may be a problem all by itself. Sending data to a server is time consuming and resource intensive compared to in-memory operations like sorting. Do you really need to do this every cycle? Regardless of how often this is done (it should be as seldom as possible), I would offload the sending to the server to a different thread so it does not slow down the UI update.

Upvotes: 1

Related Questions