I am developing an Android application, and when I start my application 2nd time I am getting force close error. Following is my logcat:
06-07 16:08:12.763: ERROR/AndroidRuntime(3293): Uncaught handler: thread exiting due to uncaught exception06-07
16:08:12.773: ERROR/AndroidRuntime(3293): java.lang.NullPointerException06-07
16:08:12.773: ERROR/AndroidRuntime(3293): at com.androidpeople.tab.MobiintheMorningActivity$t2.run(MobiintheMorningActivity.java:209)06-07
16:08:12.773: ERROR/AndroidRuntime(3293): at java.lang.Thread.run(Thread.java:1060)
Your logcat capture is telling you that in your source file MobiintheMorningActivity.java, at line 209, you're using an object which is null. Seems pretty straight forward.
To prevent the application from crashing place try{//insert code} catch(Exception e){//todo when something fails}
On the NullPointer, try debugging your program and locating the null
Huh, I feel that I should give some more useful comments than those stupid answers from Captain Obvious fellows. Usually such problems happen because developer doesn't fully understand Android Application life cycle. When you start application second time, actually you re-starting an Activity, not whole Application, so for example static data may remain from previous activity launch, even you received onDestroy() event for that activity. If you created any threads, they may remain alive (if you don't take special actions to stop them gracefully, which is not often a trivial thing - for example in my case a thread was reading data from InputStream.read(), a blocked call ending somewhere in native code, and it was not possible to interrupt it, either via Thread.interrupt() or via InputStream.close() called in other thread. But it is another story).
So, from design point of view, if you're using threads, you must keep in mind that you may be attempting to start a new thread while the old one hasn't finished yet.
Whole application will be fully destroyed when OS decides so, when it will need to recycle memory. If your app is running some threads in background, the app may be considered alive, even you do not have open activities at the moment, and the app may avoid recycling, causing some sort of memory leak. This is considered as a bad coding style.
In your case the thread seems to reuse some old data, which you probably expected to be re-initialized by Activity re-start. Or you may have another thread concurrently running from previous launch and sharing data with Activity being started second time, and it reads/writes data while you're initializing them in the second start of the Activity, for the second start of the thread.
So you need to make sure that you do not start another thread before the first one quits. You may consider using a Local Service for such purposes, but you would need to launch threads for background activities (to not perform them in main event thread of the application, which is common for services and activities in the same Application instance), or in AsyncTask. A Service simplifies things a bit because it is not interrupted by Activities start/end, so you can somehow handle an async process (in your thread) between activities restarts. So activities should put requests to service to perform long jobs, and query its state from service (or receive notifications, for example via listeners, which quite OK for local services). So, starting an activity, you should check what the server is doing - probably it already performs a job from previous activity start. Your activity may request to stop the job (if you already didn't do so when previous activity finished), and wait for job cancelation, which generally may be not a quick thing, and should be made asynchronously). Of course you may implement the same approach without a service, just in that thread.
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 have a long running background task that I would like to start when the app launches and shutdown when the application shuts down. I'm already quite aware of the activity life cycle and what gets called when an activity gets created and destroyed.
I'm coming from an iOS background, and over there we have some calls that are made during application startup and shutdown. Is there something similar in the android world? I've searched a lot and all I'm finding are answers relating to an activity, not the entire application.
(Android is relatively new to me, so I may just not know the correct terminology to search for.)
EDIT:
I'll try an be a bit more specific. I have a background task that needs to be continuously running while the user is using the application. It will be streaming data from a server continuously while the application is active. It does not need to run when the application is in the background. It doesn't seem to make sense to me to tie the startup / shutdown of this background process to any one single activity since it may not be the same one activity that starts up when the application becomes active.
I am (possibly mistakenly) assuming that the OS takes care of starting / stopping background threads when the application resumes and pauses. If that is, in fact, the case, then all I really need to do is spin up the background task when the application first launches, i.e. when it is loaded into memory and becomes active for the first time that session.
It doesn't seem to make sense to me to tie the startup / shutdown of this background task to any one single activity since it may not be the same one activity that starts up when the application becomes active.
That's reasonable. It is somewhat difficult to implement, though.
I am (possibly mistakenly) assuming that the OS takes care of starting / stopping background threads when the application resumes and pauses.
You have it exactly backwards. Android pays not one whit of attention to any threads that you fork yourself, directly or via thin wrappers like AsyncTask.
In addition to that point of confusion, you appear to be equating "user switching to another app" with "app shutdown". Those may be the same thing in single-tasking operating systems. They are not the same thing in Windows, OS X, Linux, Android, etc.
So, what you seem to be seeking is having a background thread running doing this streaming work while your UI is in the foreground, and then stop when your UI is in the background. The problem is that there really isn't a straightforward way of accomplishing that in Android.
One close approximation would be to create and register a custom Application class, where you override onTrimMemory(), and stop your background work when you get to TRIM_MEMORY_UI_HIDDEN, TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_MODERATE, or TRIM_MEMORY_COMPLETE -- whichever of those that you encounter first. If, when one of those arrives, you determine that your streaming thread is still outstanding, shut it down.
In terms of startup, you could use onCreate() on that same Application singleton. The problem is that this will be called on any process creation, which may include scenarios in which you do not have UI (e.g., you are responding to some system broadcast, like ACTION_BOOT_COMPLETED), or possibly your process is going to parts of your UI that do not depend on the streaming. If you have none of those scenarios, then onCreate() in Application would be fine. Otherwise, kick off the streaming in onCreate() of whatever activities need it.
While normally we manage long-running threads with a Service, that is for cases where we explicitly want the thread to continue after our UI is in the background. Since you do not want that, you could skip the service.
It depends on what you want to do exactly. When you're just interested in the app starting for the first time you could #Override onCreate().
Or maybe you want to use onResume() as this will get called whenever a user brings the app to the foreground.
But this really depends on what exactly your background task is doing and what you want to do with it, to get an exact answer you need to provide more details.
Here is an overview for the actiity life cycle that should help you:
You can extend the default Application class and implement it's onCreate() method to detect when the app is launched. There is no corresponding method for when the app gets closed though.
Do not forget to specify it in the Manifest file.
In Android the application isn't shut down unless the system runs low on memory. You won't get a warning about that, it will just call your Service's onDestroy lifecycle method. If you want to do it when the Activity is visible on screen, use onStart and onStop. If you want to do it when the Activity is resident in memory, use onCreate and onDestroy.
I have doubts when it comes to Services.
I know the service runs in the background, but I thought you necessarily needed to create a thread within the service, otherwise it would block the main thread and you would get an ANR error.
I thought I got it! But then I read this in the Android Developer guide:
…if your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service will slow down activity performance. To avoid impacting application performance, you should start a new thread inside the service.>
The paragraph mentions "intensive or blocking operations", but doesn’t mention an ANR error, it mentions performance. So how a service works?
Supposing an Activity starts a Service. Does the Service run by default in the background of the main thread? Meaning that you can still use your activity while the service is running, but since your Activity and the Service are sharing the main thread’s resources, it would slow down the performance of your activity, and if Service is doing CPU intensive work, it could leave no resources for the activity to use, and eventually you would get an ANR error.
The best practice (but not necessarily, if the service is doing light work) would be to start a new Thread within the Service, now the Activity and the Service are using their own thread’s resources. Then you could close your activity, but Android keeps the service thread alive.
Is that it? Thanks =)
I thought you necessarily needed to create a thread within the service, otherwise it would block the main thread and you would get an ANR error.
Correct.
The paragraph mentions "intensive or blocking operations", but doesn’t mention an ANR error, it mentions performance.
Feel free to file a bug report at http://b.android.com to get them to improve this portion of the documentation. :-)
Does the Service run by default in the background of the main thread?
The lifecycle methods of a Service, such as onCreate() and onStartCommand(), are called on the main application thread. Some services, like IntentService, will provide you with a background thread (e.g., for onHandleIntent()), but that is specific to that particular subclass of Service.
and eventually you would get an ANR error.
Yes.
The best practice (but not necessarily, if the service is doing light work) would be to start a new Thread within the Service, now the Activity and the Service are using their own thread’s resources. Then you could close your activity, but Android keeps the service thread alive.
Basically, yes. Here, "light work" should be less than a millisecond or so. Also, some things that you might do are naturally asynchronous (e.g., playing a song via MediaPlayer), so it may be that the Service itself does not need its own thread, because something else that it is using is doing the threading.
I'm using Apache Commons to make my HTTP calls, and in my activity I have a thread that makes the call. If a call is made by a device and is sitting there waiting to connect (imagine that the network is congested and the call is taking some time) and in the mean time, the user exits the app and the Activity is backgrounded. What happens to my call? For that matter (come to think of it) what happens to any thread that was started within the activity? If I have a thread that's sitting there and doing its thing (whatever it is) and the activity is closed, do I have to handle killing the thread myself onPause()?
Edit...
So, given Ted Hopp's answer, what is the right way to kill the Apache request? I'm looking through the Commons documentation and there are a bunch of methods that *look like they would do the trick, but since the doc is so lacking in details (why even bother with a doc if you're not going to specify things?!) I'm wondering which of those methods I should call on my HttpConnection object before killing the thread that my connection is sitting in?
Closing an activity has no direct effect on the process in which the activity is hosted. All other threads continue running. You should override one or more of the life cycle methods (onPause, onDestroy, etc.) to detect that the activity is finishing and interrupt or otherwise terminate running threads. The activity method isFinishing() is useful for distinguishing between an activity being shut down and one that is being destroyed and restarted due to a configuration change.
Your thread should be written with a method to cancel execution. With apache-commons in particular, that method should have two steps. First, you should call abort() for the method that you passed to your HttpClient.execute() method. Second, you should close the connection itself:
client.getHttpConnectionManager()
.getConnection(client.getHostConfiguration()).close();
Actually, if you do just the last step, that should actually suffice to throw an IOException in the method and stop everything.
Google strongly advises developers not to make HTTP calls in an Activity. Service is the recommended model. Android apps are going to be paused for many, many reasons. Some of the most common are to answer a call, sms or email. I doubt that you want to cancel the call, and therefore have the user wait for it again when he/she returns, when it could all happen in the background.
The best option is to use a Service or IntentService to make the call and persist the data (perhaps into an SQLite database). When the Activity is resumed, it can simply check for new entries in the database.
If you haven't already seen it, check out the "Developing Android REST Client Applications" from Google I/O 2010. Be sure to notice the PDF download link.
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