I have an application that uses a webservice to get information and save the changes made by the user.
currently I have one service that runs while the application is open, and it has public methods for each operation. the trouble is that service is growing considerably and I'm thinking refactor, but the question is what is the best way?
I can think of the following options:
Deferred services the current service and that all are initialized at boot time application
Create small services and that these are initialized by local broadcast
although I have doubts about performance. Can give me some clue or example about which method is better, do not really care that changes are instantly synchronized, these are stored locally and can be synchronized when possible. Data sent are not many, so the synchronization is relatively fast
Synchronization processes are something like
Check if there is new data (I have several types of data, these are the ones that are growing)
Synchronize user preferences
Most likely there's no point of having Service running all the time. Instead, I'd go for IntentService. If possible, I'd also condifer using push notification (like GCM) so the server could let my app know that there's new data to fetch (or maybe even send it to me if you'd fit in the GCM payload limit).
Related
So, I want to learn this synchronization strategy instead of just using the simpler MessageAPI, but am really struggling with how to successfully implement this.
My project is like this: I make queries to download a small amount of text from an API, via my phone. I will make these queries every so often, haven't really decided on how often just yet. The data will update the watch, which should hold onto the last data received. After that first download occurs, I send data using a DataMap, to the Android Watch. I only send that once, because I believe that sets up a channel to continually send updates when ready. If that is wrong, please correct me.
My main question is this: what if the Android phone's app closes? Then the data object goes to null, and gets sent to the Watch as null? Or, should I send an object from a long-running service or shared preferences on the Android phone, so that the object is never null?
Think of the Data Layer as more of an event system, i.e., you update your data and you're notified on the other side when the data is updated (created, changed, or deleted). You don't have to worry about if the Activity is killed after that. Even if the data was 'deleted', you would be notified it was deleted.
On the Wear device, you would listen for the changes via a Service or Activity and update UI, DB, etc. accordingly.
It probably make sense to read through this Android training guide. (It isn't too long.) The Handling Data Layer Events section is probably the most useful.
I'm currently developing an mobile application and rest service. The mobile application executes lots of calls to the service even if no update is required and data didn't changed. In order to remove this overhead of rest calls I'm planning to implement GCM (Google Cloud Messaging).
My strategy would be the following:
Load all required data on application startup. When data change was recognized on server side a push notification will be sent via GCM to affected devices to make partial refreshes of data (via specific rest calls). Advantages of this would be less overhead at service side, because there are no unnecessary rest calls and a more fluid user experience in my opinion. Disadvantage is that the app is dependent on GCM Messages and that they arrive in time.
I'm unsure if this is the right strategy for this. Could someone maybe point me in the right direction and tell me if this is a good practice?
We could use more information before answering details...
I'm unsure if this is the right strategy for this. Could someone maybe point me in the right direction and tell me if this is a good practise?
I will consider for the sake of giving an overall answer that:
A - User is not always with the application "online", neither has network, not even a desire to have updated info at all times.
B - User is eletronicaly litterate enough to understand difficulties with the program.
With those in mind, then what would be a good approach is:
Poll relevant data, store them locally. At this stage, one would consider the relevant informations that user would have and store them, with a date flag.
Once a flag goes "old" (below your threshold), re-query that data.
Operations follow 2 directives... When observing a data, check its state, show the user if its recent or not, and if its not, poll it. If it is, if the user selects operations on it (POST mostly), re query the data.
This way, you have no static overhead, if users dont have the app on foreground. Also, should they use your "always online app", they understand that network is a necessity.
My app has a UI and a connection is made to a bluetooth device which is periodically sending barcode scan data to my app. I then want to cache this data in a sqlite db and have another process push this data up to a web server.
I have managed to get the UI and bluetooth scan process separated by using an Intent Service for the scanner component... The thread in the intent service connects to the bluetooth device and loops endlessly pulling in new scan data as it comes... communicating with the UI via broadcast messages as it needs to.
So now I need to handle storing the data in a sqlite db and pushing it up to the Internet.
I'm thinking I can insert a db row directly in the intent service loop I already have working for the bluetooth data... would I do that by firing of an async task or something like that?
Then, would I have a completely different intent service running and looping endlessly checking for new records to be processed and pushed up to my web server via an http post?
I guess the main reason I'm thinking of using intent services is that they seem to keep running even if I lock my phone and put it in my pocket... has worked so far for the bluetooth barcode scanner... can scan away happily with my phone locked and in my pocket.
I also need to handle the reality that internet won't always be available... hence the sqlite db... kind of like a safe buffer to store data until it can eventually be pushed up to the Web server.
Am I going down the right path? I'm really new to Android development and even after much research I'm still unsure about my approach.
You can store data or communicate from IntentService onHandleIntent() directly. You don't need to run it in separate thread, unless you want reading bluetooth to continue ASAP.
Handling everything in an infinite loop smells. Also keeping service alive depends on few factors. If IntentService dies, it won't be restored because by default IntentService.onStartCommand implicitly returns START_NOT_STICKY, or START_REDELIVER_INTENT if you call setIntentRedelivery(true) on this service. Check Service javadoc for more info.
If you can scan bluetooth periodically then I would consider kind of scheduler. For that you would probably need to implement Service, not IntentService and handle background thread yourself. Alternatively, you could use a Timer. These are more hints, not ready solution. Since you asked about direction, I assume you will investigate solutions yourself.
Depending on handled data you could separate DB operations and network to separate services. Think about them as modules which are decoupled. You will benefit maintaing this code in the future and in case one service goes down due to any reason, the rest will keep working. It depends on data size because it's not a good practise to push heavy data between service/activities(data is serialised and deserialised every time it is sent).
If DB is just a buffer/queue then maybe use it directly after reading bluetooth data. In other words queue data for sending. Create second service for HTTP communications. Don't push entire data to second service, just inform it about(knock the door :)) and let HTTP service access DB by itself. I would wrap DB in ContentProvider and access it from services.
There are probably different techniques out there too, but that's what I thought about it in the first place.
I'm building a program which interfaces with a device which runs its own internal web server. I communicate with the device via a web API.
Basically what happens is that a GUI is presented to the user, where the user can make certain modifications to the device. These changes are communicated to the device, and results are returned through XML. The device needs to converse with the program in the background more or less continually (say every 15s or so) to update certain values to the user.
My structure that I'm envisioning is something like this:
UI - Main - Networking - XML Parser.
I'm looking for advice on how to manage these. I understand the UI thread should be separate to provide a smooth experience to users. I also understand that the networking should be at least an asynchronous task. I'm not so sure about how to handle their interaction, and make sure things are happening smoothly and effectively.
My idea is that Main will handle passing data around, telling the networker to send specific messages or changes, passing the returned XML to the parser, and then passing the parsed values to UI for handling.
I'm curious though for advice beyond that.
Have a look at creating a service that is created with your Activity. Without knowing the details of your plan, a Service looks like the optimal solution to perform all the heavy work.
UPDATE:
You could have the calls to web API run in a Service and, when needed, update the UI through an interface. You would have to instruct the Service to run on its own thread, so thread safety is an issue, but less trouble in the long run than using an AsyncTask.
Have a thought about using Google C2DM.
In your case,
Pros -> Less battery use, coordinated network traffic, Don't have to run a continues service and doesn't have the potential of being killed when the device runs out of resources.
Cons -> You have to post the results manually back to your internal server, and server should know which request the device is replying to. Communication is disconnected and may not be real-time. Requires a google account on the device and Google market.
I'm currently learning to develop for Android and I'm having a somewhat hard time figuring out when and how to use services. I have already seen the numerous questions asked about very similar things, but I can't quite find the exact answer to my questions.
I have an app which talks to a restful api. I fetch several lists which I would like to cache in memory and only update if the user hits a refresh button, or certain activities are created. If a list is refreshed, sometimes several activities need to be notified, so that they update their content (if they are on screen at the time). I store the data I retrieve in value objects.
On a non-android app I would usually create a sort of dataproxy class in a singleton pattern. I could ask the dataproxy to update its data via http request, and then it would send some kind of system-wide notification as soon as the data is changed, so the interested views can all be updated. I hope this makes sense.
My question is now: How do I do this the android way? Do I bind and unbind to a dataproxy service, which I can actively ask to fetch certain data? Should I do my non-persistent caching in this service or somewhere else? Do I need AIDL, or can I just use normal objects for moving data between a service and an activity? Although I find the android dev guide pretty well written and useful, I haven't found much information on services best practice.
Thank you in advance!
How do I do this the android way?
You assume that there is a single "android way".
Do I bind and unbind to a dataproxy service, which I can actively ask to fetch certain data?
You can either bind, or send commands via startService().
Should I do my non-persistent caching in this service or somewhere else?
If you're sure that you only want it to be in RAM, I'd lean towards static data members. Make the service be the "do-er", not the store.
That being said, I'd treat this more as a synchronization pattern, with the real store being a database or directory, with a cache in RAM. Users will find this less frustrating -- under your current plan, if they are in your app, then take a phone call for a while, they'll have to have you download all the data again.
Do I need AIDL, or can I just use normal objects for moving data between a service and an activity?
If they are all in the same process, normal objects is fine via binding, or use Intent extras for the command pattern.
Now, back to:
How do I do this the android way?
Option #1: Wrap your store in a ContentProvider and use ContentObserver for changes.
Option #2: Have your service send a broadcast to your package when the data changes, so the foreground activity can find out about the change via a BroadcastReceiver registered via registerReceiver(). Other activities simply grab a fresh look at the data in onResume() -- the only one that immediately needs to know of the data change is the one the user is interacting with, if any.
Option #3: Use the binding pattern with the service, and have the foreground activity register a listener with the service. The service calls the listener when data is updated. Once again, ather activities simply grab a fresh look at the data in onResume()
Option #4: Cook up your own listener system as part of your static data members, being very very careful to avoid memory leaks (e.g., static reference to an activity or service that is destroyed, preventing its garbage collection).
There are probably other options, but this should get you started.
The Google IO session mentioned by Andrew Halloran:
http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html
Check out the Google I/O session videos. I implemented REST api calls the easy BUT wrong way. It wasn't until watching this Google I/O video that I understood where I went wrong. It's not as simple as putting together an AsyncTask with a HttpUrlConnection get/put call.