I'm quite new to Android development.
When is it a good idea to create an Android Service instead of just using a simple Singleton class?
Take, for example, the data layer downloading information feeds from the internet.
Using a Service seems too much for some cases but sometimes I might need access to a Context so I'm a little unsure about how to design the app.
If it is okay for your process to be killed (along with the singleton) immediately after the user leaves its activities, then use a singleton. If you need it to continue running for some duration after that, use a service. If you would like to continue running after the user leaves it, but can live with it not because the user is now on to something else where memory is needed more, then use a singleton.
The decision between these two only comes down to the lifecycle of your app. For this purpose, that is all a service does -- ask the platform to modify its management of your process. If you need a context in a singleton, just use Context.getApplicationContext() to retrieve the global context for your process.
Related
I have an application which play music. I can remotely add music to a device.
I use a service to be able to run it even if myapplication is not started.
I have an custom adapter to display musics in my activity, but musics data are in my service class.
How can get the data from the service and use it to my custom adapter to display musics ?
I found some solutions like to put my objects in a derived Application class, but if all my activities are destroyed I think the application is destroyed too, isn't it?
Thanks
Use your suggested solution of putting the objects in a derived Application class.
Your Application will not get destroyed if you still have a Service running. That is the beauty of using this technique - as long as any Activity or Service is running in your app, the Application lives in memory.
Alternatively, a functionally similar technique is to use an explicit singleton for your data. For a long discussion on why this is better than using the application, check out the answers to this question:
Singletons vs. Application Context in Android?
The flip side of these techniques is memory management. Since the Application or singleton is always in memory, you may find you are using too much memory with all your objects. So that is something you will have to pay careful attention to.
Consider using weak references to your objects, backed by your DB or shared preferences. Read up a bit about WeakHashMap.
I need to make a design decision.
From what I read in the android developers site I think I want to implement a Service which launches an AsyncTaskLoader to load data from an OS process in the background.
In the android developers site documentation it says that AsyncTaskLoader can be used in Activities and Fragments, but no mention of Services.
Is it a bad practice to use AsyncTaskLoader in a Service?
If so, how do I collect data from a running OS process in the background? (Note: I need the collection to go on even if the app is closed/destroyed)
Loaders are generally used for UI elements that are created and destroyed relatively often, and need to access the previously queried objects without re-querying every time. A Service won't be destroyed mid load like an Activity or Fragment will, so spawning a new Thread is considered the best practice for loading data in the background in a Service.
Loaders are really for Activities and Fragments, it might make sense to consider an IntentService if you just want a good way to do some work in background threads. Is there something specific that looked useful in AsyncTaskLoader?
Either way you won't be able to keep collecting if your app is destroyed. If your app is destroyed, it's not there to do any work. A Service of some sort is definitely what you want to use to do work in the background though.
im wondering if it would be a bad idea to create a Singleton that is used between some Android Activities and a Android Service. As far as I know the static fields, in my case the Singleton, is available as long as the whole Process is alive.
My plan is to use a singleton instead of Parcelable to share data between my activities and a Background service. So my Activity1 will add some data by calling MySingleton.getInstance().addData(foo); then I would sent an Intent to inform my Service that new Data has been added to the singleton. Next my BackgroundService would handle the intent and call MySingleton.getInstance().getLatestData(); then it would process the data (takes some time). The result of the service would next be "post" back by using the singleton and fire a broadcast intent, which are handled by the Activity1 (if alive) and the Activity1 will retrieve the result from the singleton.
Do you guys think thats a bad idea?
EDIT:
What I want to implement is an peace of software that downloads data from a web server parse it and return the result. So my Activity would create DownloadJob Object. The DownloadJob-Object would be put into the DownloadScheduler (Singleton) which queues and manage all DownloadJobs. The DownloadScheduler would allow to run 5 DownloadJobs at the same time and use a queue to store the waiting. The effective Download would be done by the DownloadService (IntentService), which gets informed over an Intent that the a new DownloadJob should now be executed (downloaded) right now. The DowanlodService would retrieve the next job from the DownloadSchedulers queue (PriorityBlockingQueue) and return the Result by setting DownloadJob.setResult(...) and fires up an broadcast intent, that the Result is ready, which will be received by the DownloadScheduler which would remve the job from the queue and inform the Activity that the download is complete etc.
So in my scenario I would use the singleton to access the DownloadJobs from the DownloadService instead of making a DownloadJob Parcelable and pass it with the Intent. So i would avoid the problem, that I have two DownloadJobs in memory (one on the "Activity Site" and one on "Service site").
Any suggestions how to solve this better?
Is it true that static instances, like DownloadScheduler(Singleton), would be used by freed by the android system on low memory? So would subclassing the Application and hold there the reference (non static) avoid this problem?
If you are using the singleton just as shared memory between a background service which I assume is performing operations on a different thread, you may run into synchronization issues and or read inconsistent data.
If the data in the singleton is not synchronized, you have to be careful because you are relying on your "protocol" to be sure that nobody is reading while your background thread is writing (which may lead to errors).
On the other hand, if it is synchronized, you are risking to face anr error because the activity which reads the data may be blocked waiting the service to finish to write the data in the singleton.
As the other said, you also have to keep in mind that your singleton may be freed if the os needs resources, and that your data may not be there anymore.
I'd rather use an event bus such as otto or eventbus
EDIT:
Using a singleton as the entry point of background (intent) service is the approach suggested in 2010 Virgil Dobjanschi talk about building rest client applications for android.
The suggested approach is having a singleton that performs as controller of ongoing requests. Please consider also that request to intent service are already queued by the os, so you can throw several intents that will be processed sequentially by the intent service.
Some time ago I also tried take that as a starting point for a library, which still remains unfinished. YOu can find the sources here
What I would certainly not do is to store your data in the singleton. The approach I would prefer is to store the data in some persistent storage (such as sql / preferences / file / content provider) and let the client know of the change through a broadcast message (or, if you are using a content provider, through an observer).
Finally, to some extent this is the approach followed by the robospice library, which looks quite mature and ships a lot of interesting features such as caching.
A better idea is to subclass Application and put any long living objects in there. By subclassing Application you can properly handle startup and shutdown of the application something you can't easily do with a singleton. Also by using an Application Activites and Services can share access to the models within your program without resorting to parcelables. And you can avoid all of the problems Singletons bring to your program.
You also don't have to resort to storing everything in a database which requires lots of boiler plate code just to shove a bunch of data in there. It doesn't do anything for sharing behavior between parts of your application and doesn't do anything to facilitate communication and centralization of activities. If you really need to persist state between shutdowns great use it, but if not you can save yourself a lot of work.
You could also look into using something like Roboguice which makes injecting shared models into your Activities and services.
You might find this helpful:
what's design pattern principle in the Android development?
Using a singleton like this is not necessarily a bad idea, but you will lose it's state if Android decides to stop your process. You may want to consider storing your state instead in a SQLite database or a persistent queue (take a look at tape for a good example).
I am having trouble grasping the correct way to implement a centralized data access for different resources.
I want to have a single class, call it DataAccess.class that will call from both a SQLiteDatabaseHelper.class and a ServerAccess.class depending on what is appropriate when I call it's methods.
I thought extending DataAccess.class from a Service was the best approach so I can use ASyncTask for the ServerAccess.class. Now I am having doubts. The DataAccess.class needs to be accessible by most of the Activities in my Application, and I want it to stop when the Application does.
According to the google developer resources it sounds like a Service is well used for ongoing operations in the background but I am unsure how to handle the life cycle given the scope that I am trying to incorporate. Can I make the Service call startService() and stopService() internally when I use the DataAccess.class methods? Does it make sense to call it every time I access the Service or should this only happen once at the start and stop of the Application?
Thanks for the help,
I would recommend
1) Use all AsyncTask based solution because Service - Activity Communication is limited. (Unless of course you need to run something in the background) BUT I would love to hear the counterargument to this, why use a service instead.
2) Don't use just one Facade like DataAccess but make it specific to your app functions (ie sort of like System Services in Android).
3) You should use factories just like Android does to get the DataAcccess object you need. This addresses second part of where you get DataAccess object. Follow same model as getting and Android System service.
4) Use Content Providers where indicated and manage as indicated in Android docs.
Update: I think these are sort of the Axioms of a good solution. Not the whole thing. I will update as we consider this in depth.
I have a multiple Activity application that progresses the user from entering an IP/Host address, to entering some data (another Activity), to viewing a stream of video frames (yet another Activity). I share the Socket between the Activities by creating a singleton. Is this considered a bad pattern to use for an object that cannot be serialized?
I have looked all morning through some of these posts and others through out the web and the best that I can come up with is there is no real easy way, but this one seems very easy to me. The only other approach I think has merit is a custom Application object.
Any insight by people who have worked with singletons across Activities I would really like to hear of any problems I may not be aware of that might get me later... Thanks!!
The downside to your approach is that you cannot rely on the singleton's data structures to always be kept around in memory. Your best bet is to persist information in either SharedPreferences or a SQLite database.
It sounds like your singleton might be a good candidate for a Service. Services are meant for long runnning operations that do not have any UI. Multiple Activities can bind to a service and interact with it. Unlike a singleton, if/when your service gets killed, you will get lifecycle hooks to deal with it appropriately. You can also set it to be restarted when appropriate.