Retrieving JSON from database through service on Android - android

I am creating an app that requires a local database to be updated every time there has been a change in the server database. I want to run a service that runs every 2 minutes and updates the local database using ORMLite.
Would an IntentService be the best route to do this? Also I am getting mixed results on my searches about if all services are asynchronous or do I have to call a asynctask in Services other than IntentService.
Any suggestions on which direction I should go would be greatly appreciated!

I think what you need here is a Bound Service
It helps you deal with client-server model, where you main application can take advantage of background service. This service will do the job for you in background. With IntentService, this concept becomes a little bit different, you should handle this when you have a spefic job needed to be done in a short time ( not periodically like yours).
And because of frequent updatings , I think you should keep a socket connection to your server
to receive pushed updates from it ( I think some mail clients do this way).
Hope this helps.

Related

Getting data from server regularly even when the app is closed

I want to get data from the server and store it in a cache regularly, even when the app is closed. I am not sure what is the correct way to do it. I have listed down the possible ways I can think of. Please let me know the correct or the best way to do it. Really appreciate any help.
Create an Activity and set a repeated alarm to call a service. The service should connect to the server and download the data in cache.
From a fragment, check the last time the cache was updated and then if the data is out-dated, connect to server in a background thread and update the cache.
You can Directly Use IntentService for Frequently Updating Data
IntentService is a subclass of android.app.Service class. A stated intent service allows to handle long running tasks without effecting the application UI thread. This is not bound to any activity so, it is not getting effected for any change in activity lifecycle. Once IntentService is started, it handles each Intent using a worker thread and stops itself when it runs out of work.
IntentService would be an best solution, If you have an work queue to process. For example, if your application using analytics you will likely to send event name and related parameter to your tracking server for each user generated event. Although each event means a tiny piece of data, creating networking request on each click will result an overhead to your application
For implementation : Updating Data from Server Using Intent Serive
Do take a look at Android Sync Adapter Framework.
https://developer.android.com/training/sync-adapters/index.html
Hope this helps.

what kind of background-service to use for background request and saving

i am currently trying to get code running as a background service.
what this code does is:
send request to server with current location of the user
receive response
parse response
save into model (singleton)
and this is set to happen in a 30 sec interval again and again.
now if my app stays in the background for too long, it will get disposed by the device and that code will not be executed anymore. what would be the right kind of background service for this usecase?
one of my main concernes is that i save my data in a singleton. but if my app is disposed this singleton will probably not exist anymore.
intent service doesnt make sense imho because it runs a one time tasks and has to be restarted from an app that might already be disposed at that point.
using the alarm manager would mean that i will have to save everything out of the app (sqllite for example) and then retrieve that data when the activity is started again which sounds rather complicated.
can someone please help me out here?
thanks in advance!
You sir needs the service of GCM
https://developers.google.com/cloud-messaging/
Thats exactly what you need for your desire ;)
But it's not less complicated as sticking to background services.
Also you can do a Hack: having two services watching your service to keep on running and itself...I swear when the User doesn't stop your app manually in the menu the System won't be able to stop them itself. Foolproof.

Android notification in realtime

I have a website that sends and receives documents. I was thinking of building an Android app that notifies the user if a new document has been received, and displays document details if the notification is clicked. It doesn't have to be in real time, it could update in interval of five minutes or something.
What is the best way to update the Android app of changes in the website? I'm new to Android and I'm not quite sure where to start. I've heard of Services, BroadcastReceivers and Alarms, but I don't know if those are the right ideas.
Update: How do I update my Android db from my web db within an AsyncTask in my BroadcastReceiver? I'm worried I might have a "leak error" which sometimes comes up with my AsyncTask.
You can try to implement GCM or as the above-mentioned, work with an AlarmManager or the more efficient JobScheduler (requires API level 21!). Avoid doing heavy work on a BroadcastReceiver. Instead use the Broadcastreceiver to receive Alarms and start a Service in background. You may also have a look to WakefulBroadcastReceiver which holds a WakeLock for you. The Service could GET data from your webservice by using a REST architecture and update it's local database. Retrofit is a powerful open source library for a REST architecture. If there are new database records, you can inform the user by a Notification. Don't forget to check basic things like not starting the Service if the device hasn't got a network connection or to stop the Service after the work has been finished. I personally recommend to learn the basics first and then go to advanced topics. Good luck and pleasure.

Android app advice, multiple intent services?

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.

Android: Best way of handling continuous pulling from server?

To start of, i should mention that i'm a newbie in Android (Not that much experience in Java at all tbh), so be easy on me.
I am making an app that continuously pulls data from a server, and then returns data through a http post request. The question is, what is the best way to handle the actual pulling from the server? Should i be using AsyncTask or create another thread and let it run on that? Are there better methods for this purpose?
I will be pulling data every 5 minutes. (I am aware that this will drain the battery very fast, and i should definately be using Androids C2DM framework. But i have no experience in it before and i'm on a deadline, so this'll have to do until i have time to learn how to implement it.)
I'm grateful for any advice!
As an alternative to C2DM, you can do the persistent TCP connection between your device and the server. Then every 5 minutes your server can push a tickle to the device. Upon being tickled, the device can request the information via Http post.
Here is some sample code on how to do that.The connection stays open in a background thread even after the app has exited
Creating and Managing a persistent TCP socket: http://openmobster.googlecode.com/svn/trunk/cloud/android/connection/src/main/java/org/openmobster/core/mobileCloud/android/module/connection/NotificationListener.java
Full Disclosure: I am the Chief Engineer of OpenMobster and I wrote this code. Please feel free to use whatever you like or just get an idea if thats what you need
Thanks
Do you need to pull the data in background (even if your app is not "opened" and the android device is sleeping)? I suppose thats what you want because you mentioned C2DM. If so..the buzzwords are AlarmManager (with repeating time)/BroadCastReceiver and maybe NotificationManager to notify the user. With AlarmManager you schedule your events (every 5 minutes) and with BroadcastReceiver you receive those events and do what you want to do every 5 minutes :)

Categories

Resources