A very simple question:
I know that Android applications run in the background when they are closed. Is it possible for my application to keep working while it is in the background? For example, maintaining a timer in the application to automatically perform a function every hour?
Thanks!
Use services for doing tasks in background. more info is here http://developer.android.com/guide/topics/fundamentals/services.html.
An alarm service should meet your needs; here's an example.
To run things in the background (or outside of the main application thread) there are a few options. To do something very quick in the background the easiest way is to use an AsyncTask. It sounds like you are wanting to implement a bit more than an AsyncTask would handle though. For more longterm tasks that you want to run behind the scenes you probably want a Service.
You can have services that run, do what they are supposed to do and then exit, and you can have ones that keep running. Services have a lot of depth. You could use the AlarmService that is linked above by another user, however another approach would be to just make a simple service and use a TimerTask http://developer.android.com/reference/java/util/TimerTask.htm
Remember though, when you are doing things in the Service, they will be being done on the Main Thread, which could slow down other programs, so any logic over long periods of time needs to be accomplished in an AsyncTask.
Related
I am an iOS developer and recently started Android development. Currently I need the application to perform a repeating check regarding a remote resource (a JSON file) in the background, which I would like to:
App finished launching
Initiate scheduled repeating task in Application subclass
Application will be noticed if there are any changes in the remote JSON file and handle it accordingly
After doing some research I found that there seems to have many ways to achieve this, while I can rule out some of them, I can't really tell the differences between the rest and which I should use.
I've found that to perform a scheduled repeating task, I can use the following classes:
ScheduledThreadPoolExecutor
IntentService
AlarmManager
Runnable (with postInBackgroundDelayed / DelayedRunnable, or maybe ScheduledExecutorService?)
And I've ruled out the use of:
ScheduledThreadPoolExecutor, I've read that this is best used when multiple worker threads are needed, which in my case I only need one
AlarmManager, this will be executed even when the app is not running, while I only need the task to be performed when the app is running
And for the rest, which are IntentService and Runnable, from my understanding so far:
IntentService, needed to be started and stopped manually, tasks are invoked by sending an Intent to the service, and then the result is broadcasted
Runnable, like the block used in Objective-C, a specific segment of code to be executed at appropriate time
Other than these are there any other differences between them? Is my understanding correct? Are them both appropriate for my task? It it is the case, are there any considerations before choosing which one to use?
Thanks!
For creating long-running background task in Android, you should create a Service in your application.
Services are executed on the main thread of the application, with the highest priority as Activity, and continue to run even if the user exits the application.
Services have the following types :
Started Services
Foreground Services
Bound Services
Intent Services
In implementation of the services, you should create another thread, using for example ScheduledThreadPoolExecuter and delegate the work you want to accomplish to that thread.
For your requirement, you can create a simple service, extending the Service class, and in the onStart() method, create your thread to do the desired work for you.
I'm building a fairly simple data tracking app. Using a runnable, every 5 seconds my app checks how much data the user has consumed and updates the UI.
The app works well, and the runnable keeps going even when the app is not in the foreground, but when the app is closed, it stops.
I've never used a service before, and after reading some documentation, I'm still unsure if that's what I need. I need to be able to update the UI, and depending on the data amount, start an asynctask to update a server.
Right now this part is happening from the runnable, but from what I've read about services, it seems like interacting with the UI is difficult.
I was originally hoping that I could somehow just prevent the app from ever being killed. It's going to be used on a private system, so there's no concern of the user 'getting annoyed' that the app can't be closed, but I can't figure out how to pull it off.
Thanks in advance for any information!
Note: I didn't post any code because I didn't think it was relevant here, but I'd be happy to upon request.
Is this the correct situation to use a service?
Yes.
from what I've read about services, it seems like interacting with the UI is difficult.
It's not that hard. The easiest solution would be to use an EventBus.
Another solution without a library: The Activity binds to the Service in onCreate. The Service returns a Binder. The Activity passes a Listener to that Binder. The Service calls the listener as soon as the UI needs to be updated.
I am planning to implement Socket.io in android by this library for a chat based application. As far as I understood the library seems to be pretty good. I want to know how to maintain a single socket connection throughout the app all the time? Here I have listed out ways to achieve, in which I need the best and stable way.
Three ways
MainApplication Class extends Application
By this we have a good scope that the socket connection is maintained in the main thread( or application's life cycle) and whenever the socket instance is needed from the activity we can get it easily. But it's main thread which also the problem. It might block the main thread.
BoundService
By this way we can bind the service with the activities and we can simply use it. Doing in separate thread is the way to achieve IO/Network calls. But cross processing transfer is more expensive than directly accessing in same process.
Singleton
Maintaining connection in Singleton also makes sense. But we don't know when the instance is killed by process, because it doesn't work in activity life cycle.
If I makes sense please help me out. If not comment it out.
Edit
I have given the answer which is more suitable for me.
First of all, the Application's onCreate() is irrelevant in your use case because you can't have a thread running in the background when it was first initiated in a non service code.
Also, I would recommend using Google Cloud Messaging instead of creating your own mechanism. It would be best for the device's battery life and much less code for you to handle.
If you do want to implement that chat completely on your own, Service is your only choice. You can also combine it with a singleton, but I wouldn't recommend that approach. You can use broadcasts and BroadcastReceiver for communicating between your Service and Activity, I think it is easier than a Bound Service since bounding to the service is asynchronous and it creates a lot of mess compared to simple broadcasting.
Service for Maintaining socket connection
As per Ofek Ron mentioned Service with BroadcaseReceiver is a better idea than BoundService. Because its a tedious process to maintain communication. And I also recommend pub/sub way of broadcasting, like Otto or EventBus (I myself suggest Otto by Square, which is clean and brilliant api).
Pros of OTTO
1. Cleaner Api
2. You can subscribe and publish in/to any Activity, Fragment, Service class.
3. Decoupling. (You have to couple as less as possible in your code).
And one more point is use START_STICKY in the onStartCommand() to start service after it is getting destroyed. See this reference.
MainApplication to start the service
It's best practice to start the service in the MainApplication that extends Application. Because the application will be killed when there is a memory constraint or user forcefully closes the app from the stack. So onStartCommand() will not be called frequently like if we have implemented in Activity.
Implementing online status
You can implement online status simply by implementing Application.LifeCycleCallbacks in the MainApplication class, which has most of the life cycle callbacks of activity and will be notified in the callback. By that you can implement Online status simply without any boiler plate codes. (If anyone need help here let me know).
Uploading or downloading images or files.
Best practice is to implement by IntentService because it's running in the a separate thread. I promise which will give the best performance because it is handled by android itself, not like threads created by us.
You can combine first way and third way like:
Create Sockets in your Application and declare them as static. So you can maintain and access them every where in you application. Don't forget to create separate Threads to perform the network operations, you can use ThreadPool to manage those Thread. If you want to update your UI from those Thread you can use Handler and Message to communication with UI Thread
Before you create your own implementation of a socket.io client, you should give this library a chance: https://github.com/socketio/socket.io-client-java
I use it in one of my projects to communicate with a node.js server which is working pretty fine. Actually, all of your suggestions are correct and mostly depend on what you want to achieve. However, one context is always available: the application context. Therefore you should keep a singleton instance in the Application class and get it by getApplicationContext().
Online status of the user: here you should create a background service which is listening constantly for the users state. As there are not many information, this should be okay and should not drain the battery too much. Additionally you can send a flag if there are new information available and only if there is something new, you start another thread, which is receiving the new data. This keeps the data low.
Chat: the chat data is transfered only when the app is active. So, this should be done in an activity.
Both the service and the activity can access the singleton instance of the socket.io client from the application context. As long as you do not process any complex data on the main thread everything is fine. So, wrap your calls into separate thread and only start them when they are actually needed.
Okay, so I after playing around with the Android SDK a little I have decided to develop a full application. Not necessarily to release on the store (I don't really have the tools at my disposal to do proper QA and so wouldn't feel right; I could only test on my one personal device) it is mostly just a personal project for fun and learning. In the end, I decided on a camera application because I use my camera fairly often so it is the kind of application I would end up actually using if I made it and also because I am quite excited by the features of the new Camera2 API in Android L and want to give them a try.
Anyway, I have been thinking on the design/architecture of the application for a while and I have come across a potential problem that I cannot really resolve myself as I am not only not really familiar with GUI programming of this nature but also not 100% on Java and the Android SDK. They both sit well outside the purview of my dayjob.
Now I know enough that I really need to keep my UI thread separate from everything else, but what I am unsure about is first of all, what I should devote extra threads to (I was thinking one to handle image capture and storage, and another to handle the settings? perhaps that is over doing it) and also whether to have background threads which the UI thread communicates with through Events or simply to spawn threads as and when they are needed. Perhaps a single intermediate background thread which arbitrates between the UI thread and any background processing that needs to be done? What I mean to ask is, how do I decide these things? Are there general/best practices?
I'm really asking because I want to get this done properly and plan out the application thoroughly beforehand since in the past I have found that if I just dive right in I get confused very easily and end up losing faith and dropping the project. I hope somebody can help. It's not a question that I have found easy to phrase in such a way that Google would provide satisfactory results.
I think you might consider thinking about it this way:
The UI thread is where most stuff runs. It is also, occasionally, called the "main" thread, because it is, uhhh... the main thread.
Unless your program is wildly complex, you probably don't need to worry about an architecture for threads. All you need to worry about is getting slow stuff off the UI thread. That's it. You don't care where they go, just not the UI thread.
If you buy that, there are some nifty choices:
Intent Service: If, a bit metaphorically, the methods you need to run in "background" have void return types, an intent service is the perfect solution. You communicate with it using Intents and, since it has only one thread, tasks you submit to that thread are run in order.
AsyncTask: These are fraught with problems but people get a lot of programming done with them. They run in a pool of around 6 threads, but (surprise!) run in order anyway.
Your own Java Executor: Use this if you need behavior similar an AsyncTask, but with more control.
New thread per task: Just don't do this. Really.
In any of these cases, though, you don't really care on which threads your tasks are running. You make a policy about the number of threads that makes sense on the target device and then run your slow stuff on one of them.
...and "slow" should include all I/O: databases, file system, network, etc., as well as major computation.
You want to keep things as simple as possible. You don't need a thread to set settings, and you don't need an intermediary thread. These things are only going to create unnecessary complication. You only need to take long running operations off the UI thread.
Take a look at the structures the Android framework provides to make multi-threading easier first. This will help simplify your application. These would include IntentService and AsyncTask. If those won't meet your needs take a look at the java.util.concurrent package. Using a raw Thread is often not advisable.
Another library that could come in handy is an Event Bus like Otto. This will prevent memory leaks that can occur with using AsyncTask.
You dont need to worry about threads when it comes to image capture. When you want to take a picture you do so by opening the Camera App on the device. Here is a good way of doing that.
Android SDK provides Asynctask which does things for you in the background thread, like a network call and updates the UI once its done.
You can also use an IntentService, which runs even if you exit the app and does things like upload/download without the user having to worry about it. Loaders are useful when the underlying data often changes and you need to update UI quickly (searching contacts in autocomplete text for example).
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
Refer to this tutorial, its a good start. Hope this helps.
I'm trying to implement an android app where I can send commands to a server that controls a robot. The problem is quite "simple": I would like to keep a connection and communicate with the thread-service-task to send messages to the server, and get the responses to update UI and keep the user with the related information from the robot sensor.
So, what should be my decision? I know its probably duplicated. But I didnt find my same problem, cause I want to extend the question:
Is there any way to run a background process on an activity, change activity and keep it going? (Activity or fragment, I would go for fragments in the future).
Thanks in advance for any help!
The best solution for this is probably a Service.
A very good article on Services, including how to communicate with a background service via either Intents or broadcast events can be found at http://www.vogella.com/tutorials/AndroidServices/article.html
One typical model for your situation is to use:
Service for long running communication (taking "orders" from a queue
BroadcastReceiver to be notified about asynchronous events handled by Service
Activity to handle UI
One reference to consider looking at is here
Here is a Reference Code that uses an Android App , Arduino to Control a Bot. You can see its Structure thats what i have used in my robot as well. AsynkTasks wont be a good option in this aspect. Using a Service is a goodIdea for Long Running Communication
https://code.google.com/p/mover-bot/
Here is a Live Demo of This Android Controlled Robot.
Mover Bot
Do your work in Background and notify the result to UI thread.
Go through this for more detailed overview.
AsyncTask
It is a helper class around Thread and Handler for making threading and easy for you. Just do your task in background and publish result in UI thread.
http://developer.android.com/reference/android/os/AsyncTask.html
Thread
Use basic concept of threading in java, create your own thread pool do your task and publish your result in UI thread using handler. Mainlly, used when you need more longer running task while your ui is visible (for simple background task asynctask). It will take time in implementation but provide you more control over task management.
https://developer.android.com/training/multiple-threads/create-threadpool.html
Service
Services are used when you have more longer running task and also you want your ui to be independent from your task.
Here in your case i would prefer you should use a service for communication and use binder or broadcast manager for reflecting change in UI.
http://developer.android.com/guide/components/services.html