Correct way of Starting Persistent Multithreaded Service in Android - android

I need to create a test application that will allows the starting/stopping of a persistent background service that runs several threads in the background. (Mainly a WebSocket Server and the Tango location Service). It needs to be persistent so I can start a web browser and connect to the ws socket.
According to what I read, the application should be structured as follows:
Activity -> Service (persistent) -> (Service (Tango) + Thread (WS))
The persistent service needs to be run as a foreground service using startForeground() and as a separate process (set in the manifest) so it doesn't close when the activity is closed.
Now, I got to questions :
1) Is my current understanding correct? Or am I approaching this the wrong way.
2) If I later want to stop the service, I want to start the activity and be able to stop it from there. How does the activity know that the service is running and how does it connect to it? Do I need to implement the binding part? How?
3) Could I achieve 2) using notifications instead and closing it from there?

This is the best I could come up with and so far it seems to work. However, if someone has a better way of implementing this or more "correct" I will change to that answer.
The solution I went for boils down to what I stated above. The only thing is that I had to implement Runnable in new classes to pass the pointers around.
It is very important that no network code is executed in the main thread of the Service, that needs to be in a separate thread.

Related

Android: Should I use BroadcastReceiver vs Messenger vs BindService vs Handler

I know this look like tons of question around SO. But it's not (although I can also be wrong).
I have a long running Service (running in a separate thread using blutooth socket pooling for data in a OBD2 adapter every 5 seconds).
This Service is running in the same process and is a Foreground Service.
The user start this Service through an Activity. It then connect to the Bluetooth device and start pooling and saving data to a SQLiteDataBase.
The user can then minimize the activity and do other stuff.
When he returns (if ever, he can stop the service through a notification area button) to the application it checks if the Service is running and if so, it starts another Activity which show the data that is being pulled from the OBD2.
My question is, between this visualization Activity and the Service should I use and by this I mean the recommended or the right one:
LocalBroadcast? This is actually what I am using. Every time the service pull some data, it sends a broadcast with the data everytime it was pulled. Then in the onReceive method call runOnUiThread to update the respective View.
Messenger? As far as I know (never used it) I should send a Messenger from the Activity to the Service (much like a Handler) and in the Service it should send the Messages with the data pulled. But from this I would get a RemoteObjectException if the Activity was destroyed (like I said, the user could just minimized the activity and then it got GCed). So, I would probably need a way of sending the Messenger to the Service every time the Activity gets created and check if it's ok to use the messenger form the Service every time (if that's even possible, I've never used this).
BindService? Should I bind to the service when I open the Activity and then get the data directly from methods in the Service? But this would probably mean I would have another thread in the Activity gets this data from the Service every time, right?
Handler? (for a moment now I realize don't know the difference between Messenger and Handler, should it be that "use Messenger when Service runs in another process and Handler otherwise)
I've seen/read a lot of answers here in SO and through the web in general.
But in the end I don't see a ultimate answer for my case. But I'm sorry if this is just because I couldn't figure it out.
Thanks in advance!
EDIT: forgot to mention, I would rather make use only support libraries and android framework stuff, I'm still learning Android and I want to understand what's happening within its own classes.

What is the best practice for always running networking android app?

I am implementing app that is going to be always running and connected to server.
So the tablet has nothing to do other than running this app, and checking the server all the time for updates to show on the screen.
What can be the best practice to keep the app always running and connected?
In my experience, i have 2 options to solve this problem:
Service always running and connected to my activity to keep it updated.
Keep the work in threads within the activity, since the activity will stay always on. The app will be always on.
My questions are:
What is the best practice for keeping the app running all?
What is the best practice to keep the app connected ? Threads within activity? or service connected to activity?
Is there any preferable structure for such application type?
thank you
Battery is something that i will always take into consideration especially when networking task has to be done. So analyze the point where the is absolute necessary to connect to server.
Whenever you server needs to contact the device use GCM push notification that will save your battery juice which you will spend in polling the server
Well for
Service v/s Thread
is concern the use service in which you should spawn worker threads which will perfrom the networking task
these threads will notify the main service thread when they are done for that you need to user Handlers in android
i will favor service over thread because if you close the activity network request will still be fulfilled once request is complete save it in some storage form(database/share pref/content provider) and retrieve it from them. Once you are done dont for get to destroy the service by all stopSelf a appropriate point or else the service will keep exhausting you phone resource. which will make you app a bad citizen.
A simple implementation of the about pattern i mentioned is IntentService which will automatically spawn the worker thread i.e you just have to override handleIntent method and do all the heavily lifting there which will not be on main thread. And IntentService kills it self when if finds itself doing nothings
The question which you have asked to my understanding is related to syncing with server you can find more about in from android docs
http://developer.android.com/training/building-connectivity.html
If you read the official docu from Android. The best solution is using a service for your kind of app. It's prepared to run continuosly in background. You can implement it to check the network in a transparent way and you can bind the information to another activity. Furthermore, it's more scalable if later you want to change your connection or requirements (it won't affect to your apps activities).
EDIT.
The good point is, that if someday for a reason your app is not in foreground. The service can still be running. Services are prepared for long running tasks http://developer.android.com/guide/components/services.html

Background Service in Android - Need Help

I need some help or suggestions regarding Background services.
Well I want to achieve this. I have an application with Some Views that application also has a Background Service that always keeps on running.
In my views there is a Button whenever I press that button, that button passes some files to the Background Service and my Background service upload that file onto some server.
I am done with the uploading process. Now I want to know that how can I make a Background Service that always keeps on running and on my tapping of the button it sends a file to the Service.
I am new in Background service implementation.
Please guide Friends with some tutorials, suggestions or guidelines.
Thanks a bunch
You've probably already read some of the Android Service documentation, but I suggest studying it further and looking at the Local Service Sample if you have not done so already:
http://developer.android.com/reference/android/app/Service.html
It sounds like you have already got your Service up and running, and I think the actual problem you are trying to solve now is how to communicate data from your Activity to your Service. When your Activity is bound with a Service that's part of the same application, that service is in the same process and runs on the same main UI thread, so once you get the IBinder object from the Service after binding with it, you can simply directly call the functions in that Service from your Activity. Similarly, you can pass your Service a handler object from your Activity so that the service can send messages or post Runnables to your Activity. Communication with a local Service is therefore quite simple.
So if you take a look at the Local Service Sample in the link above, you will see a section in the code where we get a reference to the Service once binding has completed:
mBoundService = ((LocalService.LocalBinder)service).getService();
After that point, it's possible to directly call methods on that Service that's in the same application. For example, you could have a method called sendFile in your Service. In your Activity, you might do something like:
mBoundService.sendFile( myStuffObject );
There are quite a number of questions on Stack Overflow regarding communicating between an Activity and a Service, and I think you'd find it beneficial to search and read these.
A standard Android service will do just fine in this case.
It will continue running in the background untill its work is finished or until you ask it to stop.
There is a topic on the android dev site explaining services in detail.
you should go for android Service that is used for Background operation . Inside the service your have use TimerTask which will be checking the Queue for every x sec and when any items present in the Queue it will pull the item and upload it to the server.
here is the link for Android Service..
http://developer.android.com/reference/android/app/Service.html
Link fro Queue.http://developer.android.com/reference/java/util/Queue.html

What to use: service or threads

I am developing an android app which fetches/uploads data from/to the web service every n minutes. This upload/download is only done when the app is running. But this might change in future.
I dont update the UI when the new data is downloaded. The UI is only updated if the user is on the current screen(app have multiple activities)
My question is what is the best approach to this problem.
I dont think service is the right approach as it sounds like an overkill(in the present scenario). AlarmManager could be an option.
Running threads inside a service be an option ..something like this .
Any pointers/suggestions would be great.
Thanks
I am using AsyncTask in my activity to ask .net web service some information and it works and easy to use.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Well, in this case, since the app would already be running during the time, either would work great, but a service can be called from anywhere within the application so this is where I would use the service over the thread.
If you want to create the thread to only be used in lets say Main.java, then thread would work fine, these are the only things that I can see really making ANY difference at all, they're really pretty close, and in this case neither gives a distinct "correct" answer, but I would choose Service
I think all approaches you noted would work ok. Personally I'd go with this:
Use AlarmManager to wake download service. Start it when Activity is shown, stop it when activity hidden.
Download service should be short lived: start it to do the upload/download and then shut it down.
If download service does get some new data, it sends a Broadcast which Activity listens to.
Just broadcast a message after your upload/download is done, and then have a receiver start the service and then have that service stop itself. And you are done.
This should be done if you dont plan on polling the server for new information or anything. Primarily this kind of approach would be for onetime update, interpret, finish. And wait until the next update. Which primarily for most cases is streaming.. but depends on what you are getting.

Android - Run in background - Service vs. standard java class

In Android, if I want to do some background work, what is the difference between
Creating a Service to do the work, and having the Activity start the Service
VS.
Creating a standard java class to do the work, and having the Activity create an object of the class and invoke methods, to do the work in separate thread.
Doing your own threads is overkill, there are solutions for this, so you don't have to worry about the hard parts of concurrency. Have a look at AsyncTask or IntentService. If you go for a service please keep in mind that your service can be killed at any time.
Well, Android provides some useful methods for making worker threads easily. Look at the Looper class definition. It allows you to send events via a Handler to be executed one after another in another thread or transmit messages between different threads.
A service is nothing fancy. Creating a Service is just a way of telling the OS that you need to do some work even when your Activity is not visible.
Depending on the application you're building it might not be an option.
Nearly every network application will have some of its functionality on a Service to allow the user change active Activity while something is being downloaded.
In an RSS reader, for example you can click 'Update all' and, depending on the current data connection, it might take a bit longer than you wish. So if you want the user to be able to get back to the Home screen and do anything else while the files are being dowloaded you'll have to use a Service.
A Service allows you to run tasks on the background while the user is not on your Activity. This doesn't mean it'll be running all the time. Check the Service lifecycle.
BTW IntentService is a service.

Categories

Resources