How to realize a persistent queue on Android

廉价感情. 提交于 2020-02-01 03:25:06

问题


My application needs a data structure similar to a queue: put data in it, receive data from it, FIFO-like. With data I mean simple strings for now, later on perhaps more complex objects. The thing is that the queue and its content should be persistent, regardless of what Android is doing. If the application gets closed and reopened (or even Android reboots), the queue should have the same state and data it had before the application was closed.

I think the queue has to use some kind of storage under the hood, preferably the internal storage of the device. Maybe you could do some brainstorming how to realize this. The queue doesn't necessarily have to run in my application, it could also be some kind of losely coupled background service if that is possible in Android (but private to my application).


回答1:


I recommend using a table inside Sqlite. I would create my own SqliteQueue that implements the Queue interface. Offer would add entry to the table. Poll would return an entry and remove it from the table. For more complicated objects you could use GSON to convert the object to a JSON string or convert the JSON string to an object.




回答2:


May squareup is a good choice.

QueueFile is a lightning-fast, transactional, file-based FIFO. Addition and removal from an instance is an O(1) operation and is atomic. Writes are synchronous; data will be written to disk before an operation returns. The underlying file is structured to survive process and even system crashes and if an I/O exception is thrown during a mutating change, the change is aborted.




回答3:


This is good library from Path:

https://github.com/path/android-priority-jobqueue

"A Job Queue specifically written for Android to easily schedule jobs (tasks) that run in the background, improving UX and application stability."

And provide many features like priority, network check, callbacks etc.




回答4:


I'm pretty there are no such data structures in Java API, but there should be no problem in implementing your own kind of Queue. Take a look at this document, which contains the description of Data Storage mechanisms in Android. I would suggest using SharedPreferences, but you may choose what fits your application most. You can extend one of the Java's collections which implements the Queue interface and add your persistence mechanisms using the Android's storage approaches. Hope this helps.



来源:https://stackoverflow.com/questions/9033476/how-to-realize-a-persistent-queue-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!