Pitfalls of Android applications - android

Are there pitfalls or the points to remember while programming for Android? I think the list will include topics on Multithreading, Persistent Storage, etc.

There are many things that could be said here.
The Android videos from Google I/O 2009 cover most of the aspects that should be kept in mind, when programming on Android. In fact, the http://android-developers.blogspot.com/ articles are the source, on which these presentations expand, and seeing them explained from some of the best Google engineers (and as a bonus you'll get a Q&A section) is a must for every Android developer, IMO.
Some of the things that could be mentioned:
Don't use floats, when you can achieve similar results with integers, because Android doesn't have native support for floating point values.
Use the debugging tools extensively, to optimize both performance and maintainability, and to avoid common pitfalls like ViewGroup redundancy in UI design, or unnecessary multiple calls to heavier methods (View.inflate(), findViewById(), setImageResource()).
Bundle your background service calls, otherwise you are waking up the OS unnecessarily and too often, while risking other services piggy-backing your call (which results in severely reduced battery life)
Prefer SAX-parsers over DOM-parsers, you lose time while implementing them, but you win time in your app's performance (and your device's availability)
Keep your UI manipulations on your UI thread, because the interface toolkit is not thread-safe
Keep in mind that orientation change destroys and creates your Activity again (I learned that the hard and painful way - this is how I started to follow the android-developers' blog)
...and many others.

Android Developers has good post about avoiding memory leaks due to keeping Context references. There are a lot of other interesting posts there too.

I wouldn't call them pitfalls per se, but always remember to take into account that this is not a computer that's plugged into a wall that can just be upgraded in various ways. You have an upgrade cycle of about every 2 years (the length of a standard mobile contract these days) and the hardware is (A) not the fastest and (B) static during that time.
Things to take into consideration:
1) How does the things your app does affect battery life? Are you splashing bright graphics all over the place? Running a lot of threads in the background? Services?
2) How much space does your application need to take up on the device? Is the information something that can be kept on a server and transmitted to the device for temporary use only when it's needed?
3) In regards to #2, is your app tolerant of bad/nonexistent network/mobile connections? How does it perform on the EDGE network vs 3G?
I'm sure you can come up with more but this is what I keep in mind while I'm writing my apps.

Related

Unity how to improve your 3dDgame preformance for mobile devices?

I have build a pinball game in unity 3d for android and for some low mobile devices it is running slowly. I was thinking about hiring a unity expert to lighten up the code so it would run better on all devices.
But I wonder if this is possible. Can you make a game preform better by changing the code? I have to add this was my first unity project and it's very messy.
Thanks for helping
Absolutely, there are plenty of ways that changes to code could yield significant increases in performance, depending on how you're currently doing things.
One of them is object pooling when dealing with frequent creation/destruction of objects, another is caching component references when they are used often every frame. And if you're still using OnGui for your interface, probably avoid it in favour of the new (as of 4.6) GUI system. But you haven't included your code in your question, so I can't give a definite solution for optimizing your code.
Chances are though, not all of your code is problematic, just key scripts. My suggestion is to take a look at the Unity Profiler to determine which areas in your code are slowing down your game the most, then take steps to try reducing the execution time. You should also take into consideration non-code problems (eg. With lighting, geometry, materials, textures). Take a look at the guide Unity provides for ideas on how to address those
If you're still having problems, then you can bring that specific code to StackOverflow and see if it can be further improved. Hope this helps! Let me know if you have any questions.

Android: Why not make every method Synchronized?

Is there any downside to making every one of your methods synchronized in Android?
Yes - it will end up taking out locks when you don't really want them. It won't give you thread safety for free - it'll just slow down your code and make it more likely that you'll run into deadlocks due to taking out too many locks.
You need to think about thread safety and synchronization explicitly. I usually make most classes not thread-safe, and try to limit the number of places where I think about threading.
The "make everything synchronized" approach is a common one in what I think of as the four stages of threading awareness for developers:
Complete ignorance: no synchronization, no awareness of the potential problems
Some awareness, but a belief that universal synchronization cures all ills
The painful stage of knowing where there are problems, and taking a lot of care over getting things right
The mythical stage of getting everything right naturally
Most experienced developers are in stage 3 as far as I can tell - with different levels of ease within it, of course. Using immutability, higher-level abstractions instead of the low-level primitives etc helps a lot - but ultimately you're likely to have to think a fair amount whenever you've got multiple threads which need to share state.

producer consumer

i have an application which has a part where some variables are written and read at very high frequency.
Is there any need of a semaphores or locks(Data consistency is not a concern in this case).Is there any chance of application terminating or crashing.I dont want to get into threads,semaphores and stuff as it is a trivial part of application.
There is not nearly enough information in your question to give you an accurate answer, but in general - if you have multiple threads, and one produces data, one consumes it, then yes, you will need synchronization.
You could use a BlockingQueue, or just a simple synchronized object, whatever is appropriate in your case... but you will need some synchronization, or else you risk random hard-to-reproduce crashes.
This is even more important when dealing with multi-core systems, which are becoming popular now.

Why are most UI frameworks single threaded?

For example, Java Swing and Android UI both use a single threaded model where a single UI thread is responsible for updating all the UI. What made the framework designers chose one thread model over the other?
Wouldn't multiple threaded UI model potentially give you more performance albeit at the cost of more complexity? I realize that the latter is a big deal because thread related bugs are nasty but I am wondering if there are any other advantages to single-threaded model other than simplicity?
What made the framework designers chose one thread model over the other?
From the horse's mouth:
AWT was initially exposed as a normal
multi-threaded Java library. But as
the Java team looked at the experience
with AWT and with the deadlocks and
races that people had encountered, we
began to realize that we were making a
promise we couldn't keep.
This analysis culminated in one of the
design reviews for Swing in 1997, when
we reviewed the state of play in AWT,
and the overall industry experience,
and we accepted the Swing team's
recommendation that Swing should
support only very limited
multi-threading.
(Read the whole article, it explains the decision in great detail and states that the exact same problems and eventual move to a single-threaded model had even occured earlier at Xerox PARC - the place where almost everything we consider bleeding edge modern in CS was invented 30 years ago)
Wouldn't multiple threaded UI model
potentially give you more performance
albeit at the cost of more complexity?
Absolutely not, because drawing the GUI and processing user actions (which is everything the UI thread needs to do) is not going to be the bottleneck in any sane 2D application.
Wouldn't multiple threaded UI model potentially give you more performance albeit at the cost of more complexity?
Not in most cases, and that added complexity would do more harm than good the vast majority of the time. You also have to realize that the UI framework must deal with the underlying OS model as well. Sure, it could work around the model and abstract that away from the programmer, but it's simply not worth it in this case.
The amount of bugs caused by multiple threads updating the UI ad hoc would far outweigh what would be for the most part meaningless performance gains (if there were even gains, threading comes with an associated overhead of its own due to locking and synchronization, you may actually just be making the performance worse a lot of the time).
In this case it's better to use multiple threads explicitly and only when needed. Most of the time in a UI you want everything on one thread and you don't gain much if anything by using multiple threads. UI interactions are almost never a bottleneck.
No, probably not. At least not when you try to run the threads on the CPU. On the GPU there is already a lot of parallel processing in various forms. Not as much for the simple GUI work, but for fancy 3D (shading, reflections etc.)
I think it's all about deadlock prevention.
Swing's components are not considered thread-safe, and they don't have to be because of this Event Dispatcher Thread. If the UI was multi-threaded, the whole app would have to rely on every component behaving itself in a thread-safe manner, and if any didn't, then deadlocks could arise in obscure situations.
So, it's just safer.
Not only that, but the same design has been chosen by Windows Forms (& .Net), GTK, Motif, and various others. I wonder if Java would have been forced into this decision by the underlying OS APIs which they interact with. Certainly SWT is forced into this situation by Windows Forms.
For more info, "EDT" is a good place to start http://en.wikipedia.org/wiki/Event_dispatching_thread
For .NET, the equivalent of SwingWorker is known as BackgroundWorker.
They are all not single threaded anymore. The modern ones all build a scene graph now and render/compose them in different threads. A Html widget does layout calculations not only in multiple threads but multiple processes.
In general with the widespread use of MVVM pattern it makes no sense for complex models. You can update the Models from any thread. IMHO this was the major reason for it's invention not the data binding argument.
You can debate philosophically if you call this still single threaded just because the mouse/key/touch events arrive all in one thread. Manipulations happen in many places nowadays. And the GPU scene graph is rendered with thousands of parallel shaders how does this apply to the question?
This is because of the nature of an UI application.
You should read the input (Mouse or Keyboard), dispatch the events, let them process and than draw the screen again.
Try do it on multi-thread process.

android, object oriented programing vs designing for performance

I am a complete noob to android but I have been programing c# for a long time. I am writing an android application and have gotten to a point where the c# programmer in me wants to start creating a loosely coupled design and and moving code into different layers, using interfaces, etc.
But then I stumble upon the Designing for performance guidelines it is telling me to avoid object creation and then it also is saying to optimize judicially.
Do I just build based on good design and then deal with performance issues as they come up?
The last thing I want to do is go through the work of building a application and have it perform poorly. Can someone point me to some examples of application that are designed well and have good performance or just make some recommendations?
Thanks
I've found AndEngine to be fairly well designed and it has to be concerned with performance since it is a game development library -- so you might pull down a copy of it and read the source.
In the "Designing for performance" document, I would point out this statement:
Note that although this document
primarily covers micro-optimizations,
these will almost never make or break
your software. Choosing the right
algorithms and data structures should
always be your priority, but is
outside the scope of this document.
An example of this would be creating a particle system. A good way to model it is to have a ParticleSystem object that holds a collection of Particle objects...maybe those Particles implement a Particle interface...this is not the place to avoid object creation. However, for performance reasons, you will want to optimize the ParticleSystem to recycle Particle objects rather than creating them from scratch every time you spawn one.
Personally, I haven't found performance to be much of a limiting factor but I suppose that will really depend on what type of app you're building.
My opinion is to build a suitable design first, test the performance, and optimize from there.
Pay more attention to Donald Knuth's quote that appear in the same article:
"We should forget about small
efficiencies, say about 97% of the
time: premature optimization is the
root of all evil.root of all evil."
Then if you are dealing with the other 3% you'll see...
As a general rule, the thing to do is keep the data structure as simple and normalized as you can. Like don't just throw in hash table data structures just because they are easy to grab. Know how to do profiling (here's my method) and if you have a real performance problem then fix it. Otherwise, the simpler the better, even if that means simple arrays, lists, and O(N) loops.
The reason to keep the data structure normalized is, if it is not, then it can have inconsistent states, and you will have a strong temptation to write notification-style code to try to keep it consistent. Those can be real performance killers. If you do those, the profiling will tell you it that's what is happening.
If you must have redundant data, I think it's better to be able to tolerate some temporary inconsistency, that you periodically repair by passing through the data. This is better than trying to intensely guarantee consistency at all times by notifications.
Another problem with unnormalized data structure is it can have lots of object creation and destruction. That also can be a real performance killer, although you can ameliorate it with the pool technique.

Categories

Resources