Monday, 28 November 2016

Background process

Aside from the most basic of Android applications, everything you build will require at least some use of background threading to perform an operation. This is because Android has something known as an ANR(Application Not Responsive) timeout, which is caused when an operation takes five seconds or longer on the UI thread, preventing user input and causing what appears to the user to be a hanging app. 
In order to avoid this, you must move longer running operations, such as network requests or slow database queries, to a different thread so as to not prevent the user from continuing to use your app. Although comprehensive coverage of threading is a large and complex subject in computer science, this tutorial will introduce you to the core concepts of threading in Android, and to some of the tools available to help you build apps that perform better by using background processes.
Generally, the system displays an ANR if an application cannot respond to user input. For example, if an application blocks on some I/O operation (frequently a network access) on the UI thread so the system can't process incoming user input events. Or perhaps the app spends too much time building an elaborate in-memory structure or computing the next move in a game on the UI thread. It's always important to make sure these computations are efficient, but even the most efficient code still takes time to run.
When an application is launched, a new Linux process with a single main execution thread is started. This is the thread that has access to the Android UI toolkit, listens for user inputs, and handles drawing to the Android device screen. Because of this, it is also commonly referred to as the UI thread
All components of an application run within the same thread and process by default, though additional threads can be created to move tasks off the UI thread and prevent an ANR. When it comes to threading in Android, there are two simple rules to remember to keep your app functioning as expected:
  1. Do not block the UI thread.
  2. Do not attempt to access Android UI components from outside the UI thread.
Reference

https://code.tutsplus.com/tutorials/android-from-scratch-background-operations--cms-26810 

No comments:

Post a Comment