开发者

Loading a large array of shorts in Android

Suppose I have an array of shorts of length 开发者_运维知识库1,000,000 and that I need this to be generated or loaded into RAM (ideally within a few seconds) when my app starts and before I get an activity thread timeout.

I'll then have quick access to its entries during runtime.

  1. How would you go about loading this to memory from file? Loading from txt file? From an SQLite file (with two integer columns in a single table, one for index and the other for value)?

  2. Is it possible for an activity to request a longer idle time before it's deemed to have timed out?


The solution to your problem would be to spawn a thread to do the file reading. This is going to be a high level overview so you can track down the relevant items. It will address item 2 first, then item 1.

First, you need to get your long running processing off the UI thread. The 'idle' time responsiveness issue (application not responding) is because you are tying up the UI thread which is needed to do other actions. The thread cannot be reading a file and drawing the screen at the same time (at least not well).

I've found the easiest way to do this is using the Java ExecutorServices. What you want to do is package the logic for reading the file or database into a java Runnable or Callable and then run that using an ExecutorService. The executor will take care of starting a thread and reclaiming those resource when they are no longer in use.

One key issue to be aware of is that, once you create another thread, you need to be careful when updating the UI. Because ui objects are not thread safe, you can only update the ui from the UI thread (common sense, right?). If you are in an activity, you can do this by calling runOnUiThread() or you can create your own Handler in one of the ACtivity methods called by the UI thread in the first place.

Sam Dufel said:

Hmm... You could really pack that down if you could come with a format to replace all the dummy entries with just a count. Eg, 10,000 zeros get replaced by a pair of flag bytes followed by 10,000

Additionally, you may see increased speed by spawning multiple read threads. If you could break the file up into two files which would allow two threads to execute simultaneously you could see a significant speed up (depending on what else you need to do to the data). A sort of divide an conquer for loading up your data from file. A cursory google search should give you information on how to load shorts from a file. You should most definitely consider using a binary format given your specifications.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜