Store application global data
Someone said that android will clear singleton instance when task bring to background.
Is it true?
I realize that when I try to kill a foreground task(by using DDMS),the application auto restart it.There must be some deamon,isn't it?
Ofcouse,restart foreground application is safe to me,because as process restart,I can reInitialize my app by call Application's onCreate.
But I'm confused about background task/application.Will android kill background task and restart it just the same way as foreground app?(I hava try to kill background application,it exit without restart).Or will dalvik clear and recycle static instance?
If dalvik really really clear singlton,how do I avoid it?
Each Android application is running in a process. When a task (no matter background or foreground) is killed, actually the process is killed. It's just like the case that Java application runs on JVM, each JVM instance is a process.
There is no magic in dalvik object management which is different to JVM. I don't think dalvik will clear singleton instance. Object instance without reference will be clear on GC, but singleton should not.
In an Android application the main thread is event dispatch thread. It runs in loop, dispatches events to appropriate activities, widgets or services. Writing an application is actually implementing event callbacks: there is no main() in the code you write, you never own the main thread, the underlay framework calls your code when event happens. When the task turns to background, that is without any activities visible, there is no UI event generated, so you see that the main thread is waiting on the event queue. The article Painless Threading discusses the threading model used by Android applications.
Related
I have seen some postings on this subject, but none of them have satisfactory answers.
Assume that I start a worker thread from my main (one-and-only) Activity, in its onCreate() method. Then I call finish() to cause the Activity to terminate.
At that point, the task it belongs to gets destroyed (since there are no longer any Activity in it). The app (and the process running it) may continue to exist, however, in empty "skeleton" form, so that it can be restarted quickly if desired (although it would be highly susceptible to being killed by the system).
Assuming the above is correct -- when is the worker thread killed? Is it only killed when the system actively destroys the process?
In my case, my worker thread exists as a listener for a Bluetooth connection; when received, it will fire up the desired Activity again. In this situation there is no actively running component (Activity, Service, ContentProvider or BroadcastReceiver). It seems to me that this should work, except that something is killing my worker thread.
I am aware that I could do this (and with less pain) by using a background Service. However, I'm curious about why this isn't working.
Thanks,
Barry
when is the worker thread killed? Is it only killed when the system actively destroys the process?
-> the worker thread is skilled after all its code in run function executed. It still run even when your activity is destroyed.
In my case, my worker thread exists as a listener for a Bluetooth connection; when received, it will fire up the desired Activity again. In this situation there is no actively running component (Activity, Service, ContentProvider or BroadcastReceiver). It seems to me that this should work, except that something is killing my worker thread.
To make it works, You need to have a background service in this case and make a soft/weak reference to your service from your worker thread or more simple, using EventBus to start any component from your Service as:
EventBus.getDefault().post(new BlueToothEvent()); // call in your worker thread
// do something in your service
onBlueToothEventFired(BlueToothEvent e);
Android App lifecycle has a nice example that is very on topic:
A common example of a process life-cycle bug is a BroadcastReceiver
that starts a thread when it receives an Intent in its
BroadcastReceiver.onReceive() method, and then returns from the
function. Once it returns, the system considers the BroadcastReceiver
to be no longer active, and thus, its hosting process no longer needed
(unless other application components are active in it). So, the system
may kill the process at any time to reclaim memory, and in doing so,
it terminates the spawned thread running in the process.
In short, its really not very predictable if you thread would get a chance to run until termination or process will be killed beforehand, you should NOT definitely rely on any order/behavior.
Worth mentioning separately that its fairly easy to leak your activity along with thread even if you finish() it, but if its your last/only activity it does not change the picture
When you start a thread, it is independent of the parent that started it. In your case, it is your application activity. This means that until the Run method has been fully executed, your thread will live.
If you exit the application (and therefore call the activity's onStop method), the thread will still exist, and you will cause a memory leak. It will eventually get killed by the system if you run out of memory.
Since you mentioned that you created a listener to listen for a Bluetooth connection, your thread probably dies before it receives any event (It is impossible for me to know without any code snippet). It might also crash which would be ending the thread.
There is one main (also called UI) thread in Android. That is the only thread your app uses, unless it starts one explicitly via Thread.start(), AsyncTask.execute() etc. All Activities, Services, BroadcastReceivers, etc run all of their lifecycle methods on that main thread. Notice I included Services- a Service runs on the main thread unless it starts its own Thread (the exception to that is an IntentService, which does run on its own Thread).
A Thread you create continues until the Runnable its passed returns from its run function (or of course the process is terminated). This can live past the end of the Activity/Service it was created by. However such a Thread would still live in the original instance of the component, and would not be able to access variables of a new instance if one was restarted without a lot of special work (see Loader pattern).
Is there any way to call method when main thread of application (UI thread) is finished ? I read about onTerminate() method in Application class, but there is written :
This method is for use in emulated process environments. It will never be called on a production Android device, where
processes are removed by simply killing them; no user code (including this callback) is executed when doing so.
Are any alternatives ?
Interesting question. You may get some useful answers by posting more about what your app is trying to do. Maybe there's a better way to write your app, or maybe you actually don't need to worry about onTerminate().
As a note, a UI thread "finishing" is different from an Application "terminating". The main thread doesn't "finish"; instead, the system kills its parent process. A component (such as an Activity) running on the UI thread finishes, but the thread itself remains as long as process remains (AFAIK).
The Application object is singularly unimportant in Android. An app is much more a collection of interacting components. The Application object doesn't do very much.
Is there any difference in running background threads from an Activity and from a Service that is started by the Activity? Added: The background threads do not interact with the UI.
I currently have some background threads that are launched from the Activity. Most are via AsyncTask and one is through my own ExecutorService. I would like to know if there is a significant benefit to refactoring the code to move these to a Service or IntentService.
You seem to be confused about the definition of Activities and Services. To make it clear:
Activities are things that run according to the Activity lifecycle state machine. The code in the respective handlers interacts with an event loop attached to a UI.
Services are things that run according to the Service lifecycle state machine. The code in the respective lifecycle handlers performs operations to handle things like Intents, etc..., but does not interact with the user via a UI.
Both of these, however, run on the "main thread" of the application. By itself, an Activity or a Service (or Broadcast Receiver, Content provider, etc...) is not a thread. Look at the documentation, and you will see that the Activity and Service classes do not, in fact, form a thread. Instead, they are hooks that will run inside the Android framework, and the framework will at the appropriate time call them on the "main" thread of the app.
You can create separate threads for the app, or use an AsyncTask to do work and publish it to the UI thread easily (something not so easily achieved with a Service).
Threads that are bound to Activities have the same lifecycle. So if you restart/kill the Activity, the thread will also be restarted/killed. This is a problem if you don't manage the lifecycle of an Activity. A service is good in this case. You can have the activity destroyed and still a worker thread running in the background (in the service). But be advised that, if the Android system need resources (memory for example) it will kill the services first (and then restart them according to their Sticky flag). In my opinion, there are no actual benefit in changing threads from the Activity to a Service, since you control the workflow of your activity. If the threads are heavy (and brake the UI for moments) consider putting them in a service on a separate process (in AndroidManifest put the process name of the service).
In Android documentation:
Caution: Another problem you might encounter when using a worker
thread is unexpected restarts in your activity due to a runtime
configuration change (such as when the user changes the screen
orientation), which may destroy your worker thread. To see how you can
persist your task during one of these restarts and how to properly
cancel the task when the activity is destroyed, see the source code
for the Shelves sample application.
I am confused with android services and java thread.
Please help me to understand in which scenario i should use them.
As per my understanding
Service run in background ,so do thread.
Service is to be used for activities like network operation or playing mp3 in background,so do threads.
So whats actual difference between them and when to use each of them.
Let me give an analogy.
Activities and Service are like projects.
Activities are like external projects. This is what the clients(users) see.
Services are like internal projects. There might be several internal projects for 1 external project or none at all.
You can "pause" external project but the internal project that supports it can still continue.
Main Thread is like the boss in a company
The boss should never be held up by too much work since he shouldn't be late to meetings (UI freezing) or the client(user) will be unhappy.
Threads are like employees in a company.
The more you have, the more things you can do at the same time provided you have enough equipment(CPU speed) for all of them.
Multiple employees can work on the same project at the same time but the boss should really work only on the Activities.
Always: A service of your application is usable not only by other components of your application, but by other applications, too.
A service is for use in not-GUI parts of program.
Mostly: A service is something more independent, than a thread. Service is something more long-living than a thread. Service is something more complex than a thread.
BTW, threads do not run in background only. What runs in foreground, is a thread, too.
I believe the main difference is about Android system attitude. Service is a part of android infrastructure, so android recognizes service as a working part of application and considers killing service as a last option. Moreover, if your service is killed (e.g. because of memory lack) you can say system to restart it automatically, whenever resources available again. Moreover, you can tune up service priority in order to do it as important as foreground activity. As for threads, android does not recognize a thread as important part which must be kept. So usual threads has much more chances to be killed eventually.
For instance If you have an activity which start a working thread and then go background, as android do not recognize thread as a working part, it may think that application do nothing, because no activity or service running and kill the whole app, including the working thread.
Thus when you start a Service, you are telling system something like: "Hi. I'm doing some business here, don't kill me until I finish, please." and Android pay attention to your request.
Services are more analogous to a headless Activity.
The the important piece to understand is that a Service is about managing application lifetime and the ability to keep work running when your Application is not in the foreground (no UI visible). It is also about providing the ability to expose functionality to other apps.
http://developer.android.com/reference/android/app/Service.html#WhatIsAService
Typically when starting a Service you will also start a worker Thread. There are settings in the manifest that can cause a Service to be started in a new Process but generally you do not need to do this, it makes communication with your service more difficult.
Use a just Thread in your Activity when you need to offload work from the UI thread while the application is in the foreground, but this work can stop when you are no longer in the foreground. (It is possible that your app will continue to run when not it foreground but there is no guarantee depending on a number of factors) Generally speaking Android is free to kill your Activity if it is not in the foreground, and if your App process has no Activities or Services it can be killed.
Use a Service with a Thread to do work that will take place while your app is in the background and you want better guarantee about the lifetime.
Use a Service to expose non-UI functionality to other applications.
Android Service don't run in a separate process (by default) and even don't run in a separate thread! It runs in the main thread(UI thread) of the application, therefore if you would like to do something time consuming task in the Service start a separate thread yourself, or use IntentService.
As per Android Developer Guide (http://developer.android.com/guide/components/services.html#Basics) :
A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.
If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads.
Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.
Why we need service is to avoid resource crunch.
For example you opening an application after opening an another application so at the time your app added to the background task.
While opening multiple application, ur app may killed by android system. So if ur app has service it won't be killed by the system because service is higher priority , even it may killed the app has service so that we using constant return type in onStartCommand(). Method. That's START_STICKY,START_NOT_STICKY and DELIVER_INTENT.
I have an Android application that has a need to perform work in the background and on a separate thread. For my first proof-of-concept I subclassed the Application class and inside onCreate() I spawn a Thread that does the background work. This works just great. However, I just realized that in the past I've used a service for situations like this.
The question is, is there a reason to do work on a Thread spawned from a Service instead of a Thread spawned by Application.onCreate()? The Service is supposed to perform "background" work (it uses the UI thread unless a Thread is used, I know) that is independent of the Activity and can run while no Activity is visible. Using an Application-based thread seems to accomplish all this just as well. By not using a Service it actually removes complexity because the Activity just accesses the Application singleton. As far as I know I have no need to bind to the Service.
Will I get bit by lifecycle corner cases that using a Service would prevent? That's the only concern I have over this approach, but otherwise I'm not sold on the benefits of a Service.
The difference would be if you want the thread to run in the background only when the Activity is running or if you want it to continue to run when the user leaves.
Services are capable of running in the background even when the Activity is no longer available. They are intended to be used when your app should continue to do work without any user involvement in the near future. If you run the Thread in the Service, the thread will continue to run even when the user leaves the app. This can be beneficial sometimes as the user may want you to keep downloading a really large file but doesn't want the app to continue to run in the foreground. Then, a few hours (days, months, years) later the user can re-enter the app to read the file.
If, however, you're using a thread that needs to constantly update the UI based on results, it may be more beneficial to launch it within the Activity since it has no real purpose to run in a Service. It also may be easier in your program for your Thread to talk to the UI if it's in the Activity rather than the Service. (There may be some performance benefits as Android doesn't have to handle yet another Service on it's list, but that's purely speculation on my part. I have no proof of it.)
NOTE: Threads created in Activities will still continue to run even when the Activity quits. However, this is merely because the app is still in memory. The Activity and it's thread are on a higher priority to be deleted from memory than a Service thread when the Activity is no longer within view.
If your application is not either in the foreground, or visible, then it's more likely to be killed off by the system. If you run your code as a service, rather than a thread spawned by a background process, then your task will survive for longer. No guarantees, so you still need to manage the process lifecycle properly, but running as a service is likely to give more reliable results.
See http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html