Service + BroadcastReceiver : Uploading files in the background? - android

I am in the process of making an application. I currently have a database and a method that uploads pictures (along with data corresponding with the picture/s, stored in the database) using a PHP script on the server. Neither the purpose nor the database's schema are important. I haven't really done anything like this before but have looked into it a bit. Basically the user will take a picture with the app. The picture and its data will upload if there is a network connection, but won't if there is no connection (duh). I want to have the pending images upload once a connection exists.
To do this...My current plans are to use a BroadcastReceiver to detect when the user is connected to a network then use a Service to upload the files. Is this the proper approach? How can I basically go about starting a service when connectivity exists if and only if there are pending uploads?

Your approach sounds reasonable to me in general.
You would register a broadcast receiver with your package, listening for android.net.conn.CONNECTIVITY_CHANGE.
If the activities also trigger your service, you may be able to properly handle every case with an IntentService alone, so you won't have to deal with the many questions around when to stop or start a service with a specific life cycle.
Hope this helps; you don't sound like a beginner so you'll be able to make ends meet.

Related

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.

Background app without Gui, starts periodically every hour Android

I am making an application which will check for files on storage directory and then utilize the files and upload to ssh server.
I was thinking about making a BroadcastReceiver which will start background Service on system boot, the Service will update AlarmManager which will start every hour/every day a class for utilize/upload file.
Can you give me advice if my logic is ok, or how can I improve it ?
Thanks.
This is why Google created the SyncAdapter.
You should look at the SyncAdapter example on the Android developers site.
Sync Adapters
There are a lot of moving parts; along with SyncAdapter you'll need to learn about Authenticator and ContentProvider (if you are dealing with the file system you can skip ContentProvider). This is the framework Google provides for asynchronously moving data to/from servers. You have the option to use a BroadcastReceiver if you want, but there are a couple other methods for scheduling data syncs.

Upload sensor data from Android device to remote host

I want to develop an Android application that satisfies the following specifications:
Record data from a sensor (for example the accelerometer) at an
approximate rate of 10-30 Hz.
Upload this raw data to a remote server (for example using TCP
sockets).
The user interface should be minimum, just a pair of buttons to start
or stop the recording and transmission of the data.
All the process should be unnoticeable for the user and keep working
when the screen goes off for several hours.
Battery life is not critical (it should last several hours).
Vision: I would like to analyse in quasi-real time the sensor measurements of a group of users without their intervention (apart from starting the application).
After some research, I could manage to perform these tasks separately and inefficiently. I've tried classes such as Service and IntentService, SensorEventListener, etc. I don't know if I should use Thread, Service or IntentService for each task. Specifically, I have serious problems to communicate them.
My questions:
What class(es) do you recommend to use in order to solve this
problem?
What task should be done on each of them?
If the tasks are performed in different entities (threads, services,
intentservices, etc.), how should I intercommunicate them (I'm
thinking about the recording and uploading tasks)?
I am asking for the best-practice structure to solve my problem. You do not need to go into details in terms of developing/coding the solution.
Thank you very much and feel free to ask if something is not clear enough.
David
UPDATE:
After some more research and thanks to DROIDcoder, I manage to design a skeleton for my app:
Main UI: Activity object presenting two buttons (start/stop) that
will launch a Service with the usual startService/stopService methods
Background: Service object
Awake when screen goes off: the service requests a power lock in onCreate() and releases the power lock in onDestroy(). Find more info here: https://developer.android.com/training/scheduling/wakelock.html#cpu
Log sensor values: implement SensorEventListener in the Service as usual
Upload sensor values to server: use AsyncTask in the service as described here: How to use AsyncTask
Data formatting and transmission: use GSON library + HttpClient as described here: How to send POST request in JSON using HTTPClient?
Testing: use the website http://www.jsontest.com/ to test the JSON queries
As this is only a proposition, I add it as an edition. I will post a detailed answer when the whole system works.
The questions remains: can you think about a better design for the application?
Thanks again!
Finally what I have done:
Issue 1: record data from a sensor on the background for a long period of time.
Solved using the class Service to initialize the sensor and listen for callbacks.
Issue 2: communicate the Activity class holding the UI with the Service class.
Solved using the startService(Intent myMessage) method from the Activity class combined with a switch in the onStartCommand() method from the Service class to classify the message.
Issue 3: communicate the Service class with the Activity class.
Solved registering a custom BroadcastReceiver in the Activity and sending Intents from the Service. I've used it to update a progress bar (in the Activity) during the file uploading (in the Service). An exceptional tutorial can be found here.
Issue 4: upload data to a remote server.
Solved using AsyncTask inside the Service like in this site.
here are my suggestion
Upload this raw data to a remote server
You can use JSON parsing for server communications. you will use AsynTask(Background Thread) for background data uploading
All the process should be unnoticeable for the user and keep working when the screen goes off for several hours.
You should use services for background long term processing

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.

How to structure an application properly on background processes

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).

Categories

Resources