Tag Archives: Android

Things to keep in mind before adding a Software Dependency to your project

By Agustin Aliaga, Mobile Developer at Santex

In my work experience, one basic thing I learned about software engineering is that you don’t need to “reinvent the wheel” every time you want to achieve some functionality. Open source projects have revolutionized the way we work in that we can reutilize existing software in addition to collaborating with others devs. In the web-development ecosystem, there are plenty of frameworks and tools that already simplify things like user authentication, routes, templating (client-side and server-side), state-management, database queries, web sockets, etc. On the other hand, however, sometimes the existing solutions are just not good enough or it may be that there are no alternatives at all, but that’s a completely different story.

The ability to know when to implement the feature yourself and when to use an existing solution will be a crucial asset for your team. Adopting a new library, language or technology as a dependency to build your product without extensive research could become headache in the future, so you should always ask yourself at least these questions about it:

1. Does it meet all your needs?
Sometimes you’ll find a solution for your problem that does not cover all the specific features you need. In that case, you might have to deal with forking and extending it (if it’s an open source project), and this means greater time investments and costs. Are your team and the client prepared for this scenario?

2. Is there any documentation?
If so, is it well documented? Just as an example, one of the things I like the most about Django (web framework) is the quality they put into the docs. It’s remarkably easy to find the topics you need for the framework version you’re using. https://docs.djangoproject.com/en/.

3. Is it supported by a “big” community and/or a private company? Having a company or a community behind it helps a lot when you’re having trouble and need assistance from others. You may have to send a “help-desk” ticket (probably if it’s a paid service), find information on blogs or StackOverflow, or maybe even post a question to those sites. If you’re relying on the community to help you, your chances of being helped are proportional to the popularity of the software dependency.

4. Is it an “external service”?
If you rely on services like “Google Maps API”, “Facebook Graph API”, “Google’s Firebase”, etc. be aware that they may change in the future without notice, or they could just stop working at any time (temporarily or permanently). SaaS/BaaS solutions are great but you should think twice before setting them up as a critical piece of your system. Just as an example, read about what happened to Facebook’s Parse: (https://techcrunch.com/2016/01/28/facebook-shutters-its-parse-developer-platform/).

5. Is it actively maintained and improved?
If hosted on Github, “Pulse” and “Graphs” tabs will give you an idea of the latest activity. You probably don’t want to set up an outdated library, because it could bring retrocompatibility issues to your project. Also, if it’s constantly evolving, sometimes it could mean you’ll have to update your code repeatedly.

6. Is it tested?
Some libraries use automated tools to build and test every change that is introduced (applying continuous integration tools like Travis CI, Circle CI, etc.). This makes the library more reliable.

7. Are you compromising another dependency if you adopt this new library?
Sometimes libraries don’t play well together.

8. Will it affect your product’s performance, speed, size, etc.?
You should always take this into consideration. In the “web environment”, a giant front-end library could affect the browser’s performance and also increase network transfer times. On the back-end side, you want to avoid server overloading. In the mobile world, things get even more critical because mobile phones don’t have as many resources as a desktop computer. In Android, an app that wastes memory and CPU is a real candidate to be killed automatically by the operating system.

What about Android ?

The core-functionalities that Android brings to the table are sometimes more than enough to build simple applications. You could build an entire app by using bare Activities, Fragments, Views, AsyncTasks, Services, Content Providers, Broadcast Receivers, etc.

But in my experience, sometimes this means you’ll have to write (and then maintain) a lot of repetitive/boilerplate code. In other words, sometimes sticking to the core framework means you will have to invest more time to taking care of all the details. Some examples of libraries that made me more productive in Android development are: Retrofit, Dagger 2, and Butter Knife.

You should also know that if you add too much direct and transitive dependencies (plus your own code), you might exceed the “64K-method limit”, explained by Android documentation:

Android app (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536—including Android framework methods, library methods, and methods in your own code. In the context of computer science, the term Kilo, K, denotes 1024 (or 2^10). Because 65,536 is equal to 64 X 1024, this limit is referred to as the ’64K reference limit’.”

If you exceed this limit, you’ll have to change your application to support “multidex”, which means it will have to load multiple dex files. This will produce higher compilation times, and also performance/loading issues in the app itself. So I’d recommend to always be careful with the dependencies that you add to your Android project.

Conclusion

I have seen these concepts apply not only to Android development (a technology I use every day at work), but to all software development in general. Every product relies on dependencies (whether it’s an OS, a service, a framework, a library or some other kind of software). The goal is to pick the best ones to maximize your productivity, without affecting your product’s performance, scalability, and capacity to evolve over time.

What Thread, Main Thread? Part II

By Martín Zangl – Android Developer at Santex

mobile-phones-1

If we are to understand some basic, common behaviors for approaching a simple solution using threads, we know that at some point we have to manage communication and execution order. For that, Android provides us with a bunch of concurrency and communication frameworks that are designed, implemented, and integrated in accordance with many patterns that you can find in POSA books.

Android provides differents tools according to concurrency patterns:

We can resolve many problems with one or more of the following:

  • Using handlers and other threads
  • Asynctasks
  • Loaders
  • IntentServices

Custom Handlers and Threads

As previously stated, there is only one Looper per Thread, but we can also have different handlers post messages and process them.

For example, we could define two threads with two handlers to send messages to each other.

threads1.png

For one instance, what if one of that threads is the Main Thread, we could send update messages to UI widgets and notify something happens in the other thread. Remember that if we are just using a simple pattern like observer pattern and notifying every change directly to the UI won’t work because we are trying to change the state of view object from a thread other than the main thread. In that case we could post the result or intermediate results on the handler registered to the main thread. In other words, we have an Activity, we declare a new Handler, that handler would be associated to the Main Thread – that is, the main looper – so every time we send a message from another thread, the handler will post the message in the message queue, then the looper will process that message sending it to the registered handler. Then we can update some UI widgets.

This is a pretty clean solution, but it becomes very difficult to handle the UI widgets’ lifecycle. That is to say a configuration change happens or the user changes the context often.

The worst scenario is when a configuration change happens, because in that case a new instance of the activity will be created. It would be even worse if we had references for any particular view on those messages; in that case the reference cannot be garbage collected and we’d just be leaking memory.

More in detail, every time that a configuration change happens two new messages are posted to the looper queue, one is CONFIGURATION_CHANGE and the other is RELAUNCH_ACTIVITY and this is what happens after that message is processed:

  1. calls onSaveInstanceState(), onPause(), onDestroy() on the old activity instance.
  2. create a new activity instance.
  3. calls onCreate() and onResume() on that new activity instance.

In the case that we send messages from other threads to the main thread, we have be careful. We cannot predict in which activity instance we are posting those messages.

We could do some speculation and think if any message posted before the orientation change would be handled before onPause() the leaving activity, and if any message posted a after the orientation change will be handled after onResume() he incoming activity.

 What can we do?

Fix the architecture instead of messing it up with handler.post().

Do not hold view or context references.

Remove all messages or callbacks in the activity onPause()

And the last one if you want to get fired use hanlder.postAtFrontQueue() to make sure a message posted before onPause() will be handled before onPause().

Next post we’ll talk about Asynctask, IntentService and Loaders.

About the Author – Martín Zangl is an experienced Android Developer at Santex,  passionate about his work.  Martín is continuously learning and training to investigate new technologies.

Source:
https://corner.squareup.com/2013/12/android-main-thread-2.html
https://www.youtube.com/watch?v=S1Y1Zt3lfeQ&list=PLZ9NgFYEMxp4KSJPUyaQCj7x--NQ6kvcX&index=32

 

What Thread, Main Thread? Part I

By Martín Zangl – Android Developer at Santex

mobile-learning

Public Static Void Main

As we know, every single Java app starts with call to method public static void main(). This is true for Java desktop, JEE servlets, and Android applications.

When Android boots, it uses a simple process called ZygoteInit. Zygote (Wikipedia) is a cell that can divide asexually by mitosis to produce identical offspring. This is a VM Dalvik process that loads the most common classes of the Android SDK on a thread, and then waits. When starting a new Android application, the Android system forks the ZygoteInit process. The thread in the child fork stops waiting and calls ActivityThread.main()

Here is what it’s essentially doing:

public class ActivityThread {

public static void main(String... args) {

Looper.prepare();

Looper.setMainLooper(Looper.myLooper());

Looper.loop();
}
}

Looper? What is a Looper?

Here we can find a particular concurrency pattern called Thread-Specific Storage. This pattern allows multiple threads to use one “logical global” access point to retrieve an object that is local to a thread, without incurring locking overhead on each object access.

articulo

When a Android application starts, it creates a Looper object. A Looper object contains a static ThreadLocal object, a Message Queue, and the Thread reference that created it. In other words, a Looper implements a Thread-specific event loop. Using a Looper is a good way to process messages serially on one Thread.

Looper.prepare(); This operation associates the looper with the current thread and storage it in a static ThreadLocal.
Looper.loops(); will process each message in the queue, and block when the queue is empty.

As previously said, each looper is associated with one thread. To retrieve the Looper associated to the current thread you can use the method Looper.myLooper().

An example of using a Looper with a Thread:

class HandlerThread extends Thread {
Looper looper;
public void run() {
Looper.prepare();
looper = Looper.myLooper();
Looper.loop();
}
}

Handlers is the natural companion to a looper. Looper has a Message queue and Handlers put messages or runnable objects in place and process each of them, i.e. it allows them to send messages to a looper message queue from any thread and handle messages dequeued on the thread associated to that looper.

You can associate many handlers to one looper. The looper delivers the message to one specific handler.

A default Handler constructor associates it with current the thread and its looper. We could define the other Looper if we want in order to post messages to the Message queue of whatever Looper we want.

The looper instanced in the void main method is called Main Looper, part of the Main Thread. This particular thread is in charge of dispatching events to the UI widgets that include the drawing events. All components (other Activities, Services, Broadcast Receivers and Content Providers) that run in the same process are instanced in the Main Thread.

When an application performs intensive work in response to user interactions, this single thread model can yield poor performance. If everything is happening in the Main Thread it will block the whole UI, so no events can be dispatched, including drawing events. That is when a ANR (Application Not Responding) dialog appears. In that case, we just put all the long background operations in another thread, but other problems arise in paradise – only the main thread can process UI widgets. So, we need to somehow handle communication between threads.

Next post we’ll talk about:
Using custom handlers and other threads
Asynctasks
Loaders
IntentServices

About the Author  – Martín Zangl is an experienced Android Developer at Santex,  passionate about his work.  Martín is continuously learning and training to investigate new technologies.

Source:
https://corner.squareup.com/2013/10/android-main-thread-1.html
http://developer.android.com/reference/android/os/Looper.html
http://developer.android.com/guide/components/processes-and-threads.html