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.
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).
I am lagging in basic android concept,
As per the documentation Service is running in MainThread. and Activity(UI) also running in same thread. In what way MainThread in the android application is running both components code (Service and Activity) paralelly. How android is handling this as local Service is not a separate process. Please give me detailed explanation or any specific links
You'll notice most, if not all of the "main UI thread" methods you write, are callbacks -- they are not running any single main loop, but rather are called when needed, to perform bried tasks (ie: change UI). There is clearly an android main loop that is listening and trigerring these methods.
That same android main loop sometimes also runs Services and Handler code.
As a result, basic simple Services should not kick off extended work loops, as that would prevent focus getting back to the UI methods.
Finally, if a UI method (or Service or Handler) starts doing a lot of work, the android main loop will trigger an Application Not Responding (ANR) to kill the app.
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.
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
If I raise a thread in via an Application in Android, how long does the thread life and is active?
Does a thread continue to live when the user leaves the application. If so for how long?
Until the Thread completes. You should look into AsyncTask class instead of regular Threads though.
Yeah in Android threads are like the old-fashion Java thread. They do not have a predefined lifecylvce like Services, Activities etc. If you start a new thread you must also be responsible of its lifecycle (i.e. terminate it when you do not need it anymore and keep it alive untill you need it).
EDIT: see here and this other question. As I was saying, the thread remains alive untill it has work to do. Regard that if the process of your application is destroied by the O.S. then also the thread you have created will be destroyed as well.