In the app I have an activity which has launch mode as singleTask. There are number of use cases which pass through this activity and hence it's called number of times. On stress testing the app by running monkeyrunner script and calling this activity every few seconds causes ANR's.
I guess, the way it's designed where most of the use cases pass through this activity is not correct but I am not in a position to change this design.
Is there anyway ANR's can be suppressed? I mean, adding UI operations to event queue so that it doesn't block main UI thread and doesn't give ANR.
It is unclear from the question what your activity is (or should be) doing. Probably you need a service instead.
It is common to perform time-consuming operations in background threads and deliver the results to the UI thread.
You may use the classes Handler/Looper (it it easir to send Runnables rather than messages), or use an AsyncTask. The AsyncTask is nevertheless tricky, this is discussed here: Is AsyncTask really conceptually flawed or am I just missing something? . AFAIK Google tried to fix the typical bugs and made the new behavior incompatible with the old one (namely, I have seen some misbehavior on the newer Androids that may be explained by the assumption that since some version threads doing asynctask jobs get killed after the activity that started them goes out of the screen).
I can guess that singleTask is your way to fight the fact that an activity dies when the screen turns, and a new one comes. I suggest you use singletons (they survive screen rotation but do not survive a process restart, one more thing that sometimes happens in Android). (The user switches to an app like Camera, takes a big photo, returns back -- and the activity is restarted because Camera needed memory. Have seen this in practice, but that time I did not try to find out if the whole process was restarted.)
Anyway, please add logging telling you when your activity in entered and left, including onNewIntent() and other lifecycle functions (to be on the safe side, I recommend to print the thread names as well). Then you will probably see what is going on.
Related
What is the difference between all the above?
I found various posts which were helpful but also quite confusing. According to my understanding in short this is what I came upto:
Threads are tasks that share same resources
Processes are tasks which have independent rersources. A process can
have multiple threads.
Tasks are the instructions being executed
Now this is where I get confused. How is an activity related to all
these three in android. Activity can have multiple tasks so it must be something like a process. But then what is the difference between activity and process. Moreover I read somewhere that tasks are stack of activities. It got me all confused. Ive also read that all activities run on UI thread which just make the distinction a little more confusing.
You should differentiate between Processes & Threads vs. Activities vs. Task. They aren't even really in the same category.
Let's start with the simplest one, Task's. Assuming you are not talking abouy any actual class, i.e. TimerTask, the basic concept of a Task is the following.
When a user starts your app for the first time, a new Tasks is created. You can see this by pressing the "OverviewButton", represented by a Square for the software buttons. (on Android 5.0 an higher)
A Task will not get disposed of, unless the User actually removes(swipes left/right) it from the Overview screen.
So a Task is really just a high-level abstraction for the user.
Like you alluded to, a Tasks has an Activity backstack, which is just a normal stack that is used to keep track of the "history" for the user. For example, your App is launched, your MainActivity will be at the bottom of the stack, the User enters some values and then goes on to a new Activity. Now this new Activity is above the previous one, and the user can press the "back button" at -hopefully- any time to get back to the previous activity.
Now for Processes &Thread's, a Processes under Android is very similar to a linux process, your app will usually only be working within one single process. A process gets assigned a certain part of the memory by the OS, if you're familiar with languages like C, attempting to acess memory that does not belong to your process wil cause a
"segmentation fault".
Like you said, a process may have any number of Threads, assuming the OS can manage the required Overhead.
A process will at least have one Thread, under android this is called Main-Thread or UI-Thread. Threads, very basically, allow you to do some work in parallel. You will most likely need to make use of them, for example when performing network operations.
Now for Activities, they have no direct relationship to multithreading. The currently "active Activity" is the one that is run on the UI-Thread. So all of its callbacks will be run on the UI-Thread, unless specifically documented not to.
An Activity is an abstraction used by the android framework, it exists at a fundamentally different level than a Processes & Thread's. You can call a method defined in a Activity, from any Thread you want.
A really nice question, from my little experience with android development, I'd like to contribute. Let's start from..
Processes
Ever opened task manager on windows to see open apps? Those are processes. On android, when an app is launched, a new process is opened and allocation of memory etc is given.
The activity classes,imports and threads all make a process in the Android system. sometimes you see an error message when an app crashes "unfortunately com.android.bakerapp has stopped."
This means an error causes the whole process of threads, imports, activities to close. So basically processes are parts of an app or an app in general that's running.
Activity
An activity is the heart and soul of all android apps, all Threads, preferences, views and layouts are opened by android activity class. It is the container object that holds views, passes information around and runs threads too. Activities communicate with each other through intents, objects in the class extends and methods.
Activity is the piece of code that creates and communicates UI and everything a user sees and uses. It is used to create threads. Which is discussed below.
Threads
This one is easy, a thread is basically a process to get something done, it lives and dies after its work. Imagine you have an activity with a view of picture on the screen and you want to automatically set your apps theme color to the most common color on the picture using a library.
The best method to do this without the user knowing and also confusing the main thread responsible for loading the picture into a view from a website is to open a thread using an Asynchronous task (something that runs in background) is an example of a thread.
So a thread is basically a life cycle of a task to be done, it can be continuous (Main activity views and list views) or short (Find a dominant color in a picture) or fun and multitasking (downloading a picture from a group chat while at thesame time chatting with your girlfriend on WhatsApp).
Threads are the most essential part of all activities and processes and can send,receive and process data.
Activities cannot work without threads because the setContentview and UI itself is just another thread, you can have multiple threads in one activity.
Happy coding!
https://developer.android.com/guide/components/processes-and-threads.html
I know this is old, but you can also say that a thread is the smallest unit of execution of code. Threads are scheduled to run on the CPU. A process can have one or more threads.
An application background service updates sqlite database. Therefore my activities are becoming outdated. Activity intents also contain outdated params so onCreate, onResume will crash the application. An easiest solution is to restart whole application. I don't want to add IFs to all onCreate, onResume methods in all activities to handle one special case.
I noticed that ACRA has following code executed after an exception has been handled.
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
However many people discourage use of System.exit(0). Is System.exit(0) really that dangerous for an Android application data integrity? Of course my code will close the database before existing.
Update:
I known how to use finish(), content providers, send broadcasts, read many answers here on SO, etc. However each of these approaches requires additional thousands lines of code. I implemented solution with System.exit(0) in ten minutes. The restart is so fast that it is indistinguishable from ordinary startActivity action. The db update/restart is done after longer user inactivity so the app is already suspended by the system. My app doesn't require real time syncing. During tests the application behaves correctly. This is quick and dirty solution.
Therefore I asked the question about possible side effects of System.exit(0). Not how I can do the design differently. I know that current design is not perfect.
System.exit(0) is an artifact from Java runtime, it isn't meant for Android. So in any cases using it would be worst solution.
Why don't you use Activity.finish() gracefully?
If you terminate the process you are living in, you'll loose most of the caching and restart time (~resume in the eyes of the user) for it next time will be higher.
Read more in Activity Lifecycle documentation on Android Developers.
Killing the process will not clean up any registered resources from outside the process. BroadcastReceivers, for example. This is a leak and the device will tell you as much.
You really shouldn't be updating the database schema from a background service. Do it when your activities resume.
If you are just updating your data, resuming an activity should validate the data specified by the Intent and tell the user if, for example, Item X is no longer there.
No tool is that dangerous if used carefully and for a specific, well thought off purpose.
However, In your case I do not believe System.exit() is the right way to go. If your application depends on data from a database, create a background service (or a few, depending on what you need) that will inform your application of changes and update the data. It is, in my opinion the right way to handle changes.
As for scenarios when you want to use System.exit() I personally sometimes use it when I can't recover from a critical error and no graceful degradation is possible. In those cases it is better to force all resources associated with your application to cease rather than just leave loose ends tangling around. To clarify, you should always use error handling before doing anything radical. Proper error handling is often the way to go.
But this is a very delicate topic and you are likely to receive quite a few diverging answers.
Therefore my activities are becoming outdated.
Use a ContentProvider and ContentObserver (or the Loader framework), or use a message bus (LocalBroadcastManager, Otto, etc.) to update the activities in situ.
Activity intents also contain outdated params so onCreate, onResume will crash the application
Copy the relevant "params" to data members of the activities. Update those data members as needed (e.g., from the handlers from the message bus-raised events). Hold onto that data as part of your instance state for configuration change (e.g., onSaveInstanceState()). Use this data from onCreate(), onResume(), etc.
An easiest solution is to restart whole application
It is not easiest, if you value your users, as your users will not appreciate your app spontaneously evaporating while they are using it. Do you think that Gmail crashes their own app every time an email comes in?
Next, you will propose writing a Web app that uses some exploit to crash the browser, because you cannot figure out how to update a Web page.
I noticed that ACRA has following code executed after an exception has been handled.
A top-level exception handler is about the only sensible place to have this sort of code, and even there, the objective is for this code to never run (i.e., do not have an unhandled exception).
There's an existing answer HERE that might give you some help as to why people say it's bad to use System.Exit().
This question already has answers here:
Android AsyncTask for long running operations
(4 answers)
Closed 9 years ago.
The API reference states,
AsyncTasks should ideally be used for short operations (a few seconds
at the most.)
Is the problem with a doInBackground that takes, say, 30 seconds that the thread pool might run out of threads? And if that's the reason, would it cease to be a problem if I ensure my app will never have more than one such long running doInBackground executing concurrently?
The answer given by #Walter Mundt is correct. Nevertheless, I would like to add a complement of information and give a pointer to a library that can be used for long running AsyncTask.
AsyncTasks have been designed for doing stuff in background. And, yes, it's right that if your AsyncTask lasts for two long, then you will face 2 different issues :
Activities are poorly tied to the activity life cycle and you won't get the result of your AsyncTask if your activity dies. Indeed, yes, you can but it will be the rough way.
AsyncTask are not very well documented. A naive, though intuitive, implementation and use of an asynctask can quickly lead to memory leaks.
RoboSpice, the library I would like to introduce, as proposed by #Walter Mundt, uses a background service to execute this kind of requests. It has been designed for network requests (potentially long running by nature), but it could be easily adapted to execute just long running tasks, unrelated to network. I would be glad to add a patch to it.
Here is the reason why AsyncTasks are bad for long running tasks. The following reasonning is an adaptation from exerpts of RoboSpice motivations : the app that explains why using RoboSpice is filling a need on the Android platform.
The AsyncTask and Activity life cycle
AsyncTasks don't follow Activity instances' life cycle. If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes.
And when it completes, the AsyncTask won't update the UI of the new Activity. Indeed it updates the former instance of the activity that
is not displayed anymore. This can lead to an Exception of the type java.lang.IllegalArgumentException: View not attached to window manager if you
use, for instance, findViewById to retrieve a view inside the Activity.
Memory leak issue
It is very convenient to create AsyncTasks as inner classes of your Activities. As the AsyncTask will need to manipulate the views
of the Activity when the task is complete or in progress, using an inner class of the Activity seems convenient : inner classes can
access directly any field of the outer class.
Nevertheless, it means the inner class will hold an invisible reference on its outer class instance : the Activity.
On the long run, this produces a memory leak : if the AsyncTask lasts for long, it keeps the activity "alive"
whereas Android would like to get rid of it as it can no longer be displayed. The activity can't be garbage collected and that's a central
mechanism for Android to preserve resources on the device.
Progress of your task will be lost
You can use some workarounds to create a long running asynctask and manage its life cycle accordingly to the life cycle of the activity. You can either cancel the AsyncTask in the onStop method of your activity or you can let your async task finish, and not loose its progress and relink it to the next instance of your activity.
This is possible and we show how in RobopSpice motivations, but it becomes complicated and the code is not really generic. Moreover, you will still loose the progress of your task if the user leaves the activity and comes back. This same issue appears with Loaders, although it would be a simpler equivalent to the AsyncTask with relinking workaround mentionned above.
Using an Android service
The best option is to use a service to execute your long running background tasks. And that is exactly the solution proposed by RoboSpice. Again, it is designed for networking but could be extended to non-network related stuff. This library has a large number of features.
You can even get an idea of it in less than 30 seconds thanks to an infographics.
It is really a very very bad idea to use AsyncTasks for long running operations. Nevertheless, they are fine for short living ones such as updating a View after 1 or 2 seconds.
I encourage you to download the RoboSpice Motivations app, it really explains this in-depth and provides samples and demonstrations of the different ways to do some background operations.
If you are looking for an alternative to RoboSpice for non network related tasks (for instance without caching), you could also have a look at Tape.
I believe that AyncTasks are in general still tied to the foreground activity stack that spawned them, so that e.g. if an Activity spawns an AsyncTask, the user leaves the app, and then the OS is short of memory, it will kill the Activity's process (including the still-running AsyncTask), and just expect you to restore the state and start over if the user resumes/returns to your app.
For longer-running tasks, particularly the sort where there will only be only one or a few, you probably want a Service instead, because those can persist even when your app's UI is shut down to save memory.
Disclaimer: I haven't done Android coding in awhile, so this answer may be out of date or based on a flawed understanding of how things work. I will remove this caveat if someone with more recent experience can comment to confirm; high-rep folks are welcome to just edit this paragraph away instead if they know this is correct.
I have a complex app that has background threads (that could be in a service) which, when they receive data from the internet, need to notify my main display activity (to update on of several status indicators). All run in the same process (I see no reason to do otherwise).
However, in some circumstances, these events are frequent - 5 per second. Also, the events may occur when the activity is not-visible or even destroyed. I think the only thing novel about this question is the issue of efficiency. I still target the G1, for example.
There are a number of methods mentioned in this thread, but I don't know which of these are efficient enough, and will work if the activity is destroyed. Those methods are the "Android way" which I would prefer to follow.
I have three ugly anti-Android ways that work, but they also have drawbacks:
Have a thread in the activity that is waits on a semaphore, and when released, does the update. Disadvantages: extra thread, how to handle several event types
Like #1, but use a concurrent blocking queue object. Disadvantages: extra thread, same type of event may end up in the queue multiple times (not good)
Keep a static reference to a handler on the activity, and use that to run an updater. Disadvantages: (a) may leak a reference to the activity? (b) what happens when the activity changes state? (c) multiple runnables could end up there when only one is needed.
Also, the events may occur when the activity is not-visible or even destroyed.
If your activity is destroyed, there is nothing to update. If and when the user elects to re-visit that activity, the activity can get the current information in onResume() for display.
If your activity is in the background, there is nothing that needs to be updated, either. Again, if and when the user elects to re-visit that activity, the activity can get the current information in onResume() for display.
The ONLY time you need an activity to be notified of events in real time is if that activity is in the foreground. In that case, any of the solutions I outlined in the answer you linked to could work. The binding option or Messenger are probably the lightest-weight solutions.
I have a complex app that has background threads (that could be in a service)
Not "could be" -- "must be", if they are to live beyond the scope of any given activity instance.
I have three ugly anti-Android ways that work
None of those work without potential memory leaks.
I'm designing an android app which will need to do the following steps:
user pushes a button or otherwise indicates to "sync data".
sync process will use REST web services to move data to and from the server.
the data will be stored locally in a sqlite database.
the sync process should provide status updates/messages to the UI
the user should not be allowed to wander off to other parts of the application and do more work during the sync process.
The first time the sync process runs, it may take 10-20 minutes.
After the initial sync, less data will be transferred and stored and
I expect the process to take 1-2 minutes or less.
I've been doing a lot of reading about android's AsyncTask and various examples of using a Service ... But I don't fully understand the design considerations and trade-offs of choosing one design over the other. I currently have my demo project stubbed out using an AsyncTask. After watching (most of) Developing Android REST client applications: http://code.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html# I'm left confused the design patterns described here feel overly
complex, perhaps because I just "don't get it" yet.
I come from a java, spring, web and desktop application background. Thinking and designing in terms of a handheld device is quite new to me. (What happens when the screen layout is changed? What happens when the phone rings while I'm running a sync?) Taking 2 steps back, if the initial sync IS going to be such a long running process, is there a better way for me to think about the problem->solution, the user experience, the user expectations of an application running on a phone?
Would love to hear from some more experienced android developers out there who have already wrestled with these questions.
In my opinion this is the most tricky/hard part of a mainstream/average Android development. For instance on BlackBerry this is IN TIMES easier.
Definitely you need to use a Service.
AsyncTask does not suit, because it is tightly "bound" to your Activity via a Context handle (otherwise you would not be able to update UI of the Activity from your AsyncTask). However an Activity can be killed by OS once the Activity went in background. An example reason of going to background can be an incoming call - user switches to Phone application so your Activity becomes invisible. In this case (depending on the current RAM state) OS may decide to kill one of the background (invisible to the user) activities.
Some devs workaround this by arranging a static stuff for having a long-running actions inside of. Some recommend to use Application instance. This is because static stuff and Application exist while the whole app process exists. However those are incorrect workarounds. Processes in Android are also may be killed when OS decides it is time to. Android OS have its own considerations about what it can kill and in what order. All processes are devided to 5 levels of "killability". Here is the doc where those levels are specified. It is interesting to read there:
Because a process running a service is
ranked higher than one with background
activities, an activity that initiates
a long-running operation might do well
to start a service for that operation,
rather than simply spawn a thread —
particularly if the operation will
likely outlast the activity. Examples
of this are playing music in the
background and uploading a picture
taken by the camera to a web site.
Using a service guarantees that the
operation will have at least "service
process" priority, regardless of what
happens to the activity.
Your Activity where users initiate a long-running action should show a ProgressDialog to make sure user does not do anything else while the action is running. The guide is here.
Also, you'd most likely want to use the NotificationManager for notifying the user about your long-running action completion (or failure) if your Activity is currently invisible. Here is the NotificationManager info to start from.
There are multiple considerations that you must weigh in order to best decide how to approach your situation. It sounds like you need a good comparison between the two approaches... So here is a list of similarities, and differences and additional considerations that must be taken into account when working on a handheld device.
A Service is a part of your Application that has no UI. It may be called by a UI(Activity) to be started, or may be started by any other component of your Application. When developing, you have the freedom to place it on a different thread, or even run it in a different Task or Process. This allows you to ultimately separate it from your UI. Additionally, you may start the Service to run independently (startService) or bind your activity to it (bindService) depending upon your needs. By using custom Handlers, you can set callbacks to update the UI with your progress. A Service does not necessarily end if a User changes Activities, but may be ended at ANY time by the OS.
A AsyncTask is always instantiated from the UI thread. It only allows specific callbacks, but simplifies the process of multi-threading for the purposes of relatively short transactions (as compared to dedicated separate threaded services) that are inherently tied to actions performed by an Activity. Whenever a User changes Activities, the AsyncTask is put on "pause" and may even die because there is no UI thread for your Activity any longer.
The thing that I would be most concerned about is if the app is going to take 10-20 minutes the first time, I would ASSUME that the User will either change tasks temporarily or set the phone down until it completes (which can cause all of the same complications if the phone sleeps). Given this consideration, a threaded service bound to your activity may be your best choice. To protect your UI, I would make a Progress Dialog for your Activity that receives your progress callbacks. This limits user input in YOUR app and allows your service to continue the way that it needs to. Then override the Activity onResume to check the status of your Service and if it is running. Then you can reset the Dialog immediately.
Given that this is my preferred method, I would also take into account that the OS may kill the App at any time anyway. So make sure to have some way to detect an incomplete or partial sync. Then you may resume automatically when your Activity or Service restarts.
With AsyncTask if the user goes to another Activity you can't transfer that object to the other Activity so it dies. There are tricks you can play when say the user rotates the screen or something like that, but that doesn't extend to general purpose destruction. AsyncTask can randomly die.
Google Sync is run as a Service in the background because syncing can take a while to complete. You might need to follow their path and create your own sync service that you can communicate with. Here is some thoughts how to accomplish that:
http://mylifewithandroid.blogspot.com/2008/01/about-binders.html
You can definitely communicate between Service and Activity, but it's tricky to do it right.
The choice is mainly dependent on the app design. Since both AsyncTask and IntentService stands their ground, what you may want from the app(user experience) is more important and then choose either or both. Some scenarios are mentioned below (mostly what I experienced while developing apps)
Assume apps that have feeds pages - where more than one api calls are made to make the page presentable ( /getFriends, /getDates, /getPictures etc.) you can warp all such api calls to a single AsyncTask with executor which is multithreaded and the sequence of execution doesn't matter. In contrast to IntentService which runs all calls in sequence in a single worker thread. For a high end device with multi-core the call from AsyncTask is more effective. And if you start the AsyncTask on UI thread then updating IU is a piece of cakes(read less boiler plate code). And even if an user leaves the page, with intelligent use of not holding on to the context the app doesn't crash.
Assuming you are trying to write an app which doesn't need the user to be on view/activity/fragment and the total execution time to show something is not mission critical (assume sync service or user notification/alarm) then IntentService is a better choice. (no hassle to start Asynctask on UI thread so that you don't need to write a Handler to force changes on UI etc. etc. and less boiler plate code)
From my experience - write small app for both and compare the pros and cons to get a better idea. (p.s I'd suggest take a look at the iosched app from google to get a better idea - they use both Asynctask and IntentService)
I tend to prefer the IntentService + BroadcastReceiver combo because they give you a really strong degree of control
You definitely have to make sure the UI is running if you are updating something on the screen. ASyncTask crashes were at once reported to be one of the top causes of Android crashes. This can be avoided by keeping some sort of "activityIsAlive" variable and skipping or delaying a UI update if the activity is dead.
The IntentService + BroadcastReceiver combo is a little more resistant to the crash because most tutorials tell you to shut off the BroadcastReceiver onPause or onStop. If you do not do this, again you'll have to turn off the UI update. There's a runOnUiThread command somewhere that will help you do UI updates.
The IntentService + BroadcastReceiver combo is also more extensible. You can create functions and extend BroadcastReceiver to make a more elegant REST processing solution. However, it does require more plumbing vs an ASyncTask
If you do delay the UI update, you may be able to rig it on OnWindowFocusChangedListener. When that function receives true, it means that the UI is alive.
tldr; Make sure the Activity and/or Fragment is alive before updating the UI if you are running something in the background
2015 Edit: check out Loaders as well. A little harder to grasp because there's a lot going on behind the scenes