Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 6 Threads, Handlers, and Programmatic Movement.

Similar presentations


Presentation on theme: "CHAPTER 6 Threads, Handlers, and Programmatic Movement."— Presentation transcript:

1 CHAPTER 6 Threads, Handlers, and Programmatic Movement

2 Chapter objectives: Understand the benefits of multithreading on Android Understand multi-threading fundamentals. Know the Thread class and the Runnable interface Understand an AsyncTask Learn to implement canvas movement using surface views Learn to communicate between threads.

3 6.1 Multithreading and Multi-core Processing Android uses processes and thread management models to manage running applications, services, and the other elements of the system When an application does several things at once it is called multithreading Other terms are used for multithreading, such as parallelism and concurrency A multithreaded Android application contains two or more threads

4 Multithreading enables programmers to write very efficient applications because it allows the utilization idle time that may accrue while other segments of code are being processed Each thread runs as a separate path of execution that is managed by its own stack, the call stack The call stack is used to manage method calling, parameter passing, and storage for a called method’s local variables

5 Multitasking can be subdivided into two categories: process-based multitasking and thread-based multitasking Process-based multitasking is the feature that allows a device to execute two or more programs concurrently. In process-based multitasking, an app is the smallest unit of code that can be dispatched by the scheduler.

6 In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code This means that a single program can perform two or more tasks at once This single thread is responsible for handling all the UI events Even a simple single-threaded application can benefit from parallel processing on different cores

7 Categories of operations that can be carried out on separate background threads are as follows: Heavy calculations An Object’s long initialization Networking Database operations

8 6.2 Main Thread and Background Thread Android UI threads are distinct from background threads When an activity is created, it runs by default in the UI thread of the application All the commands issued by the Android operating system, such as onClick, onCreate, etc., are sent to and processed by this UI thread.

9 When a substantial amount of processing is performed on the UI thread, the application may be too busy to respond to messages sent by the Android operating system If an application frequently computes an elaborate game move on the UI thread, the I/O operations of the system, such as processing incoming user input events, may perform sluggishly or can be blocked.

10 When writing multithreaded applications in Android, it is a good idea to keep several things in mind about the UI thread: The UI thread should not perform tasks that take longer than a few seconds The user interface cannot be updated from a background thread. An Android application can be entered from an Activity, Service or a Broadcast Receiver, all of which run on the UI thread.

11 6.3 Thread Approaches From the main UI thread, programmers can create other threads This is done by instantiating an object of type Thread The Thread class encapsulates an object that is runnable. There are two ways in which a runnable object can be created: 1) Implement the Runnable interface 2) Extend the Thread class

12 The Runnable interface abstracts a unit of executable code You can construct a thread on any object that implements the Runnable interface Runnable defines only one method called run(). An application that creates an instance of Thread must provide the code that will run in that thread

13 A Thread class can also be constructed that implements the Runnable interface The Thread class itself implements Runnable, through its run() method

14 6.4 UI Modification and the Handler Class A Handler is part of the Android system’s framework for managing threads and is designed for inter-thread communication It combines features from a BlockingQueue and a message listener. Interaction between an Android thread and the UI thread is accomplished using a UI thread Handler object and posting Messages and Runnable objects to a message queue A Handler object created on the UI thread exposes a thread-safe message queue on which background threads can asynchronously add either messages or requests for foreground runnables to act on their behalf

15 When a Handler is created for a new thread, it is bound to the message queue of the thread in which it is created The Handler will deliver messages and runnables to this message queue and execute them as they are retrieved off the queue.

16 6.5 Loopers Looper is a class within the Android user interface that can be used in tandem with the Handler class to provide a framework for implementing a concurrency pattern

17 Background threads can push new units of work onto the MessageQueue at any time The UI thread processes the queued units of work one after another If there are no work units on the MessageQueue it waits until one appears in the queue Processing the MessageQueue can be quit at any time and units of work can be removed from the queue

18 A Looper is the mechanism that allows these units of work to be executed or processed sequentially on a single thread A Handler is used to schedule those units of work for execution by pushing them onto a MessageQueue.

19 6.6 Canvas Movement and Views Programatic animation can be achieved through the use of a canvas A canvas is provided by View.onDraw() The most convenient aspect of this feature is the provision of the pre-defined Canvas, which is automatically supplied by the Android framework

20 6.7 SurfaceViews Android provides a SurfaceView class to construct objects with a dedicated drawing surface that can be updated on a background thread SurfaceViews contain a rendering mechanism that allows threads to update the surface’s content without the use of a Handler

21 SurfaceView is derived from the View class. It provides more resources than Views and was created with the objective of delivering a drawing surface for a background thread

22

23 6.8 Efficient Threading There are obvious advantages of multithreading, such as the provision of greater responsiveness by using idle time to perform background tasks The employment too many threads can lead to a sluggish application.

24 The impact of having too many threads in an application can result in the following two conditions First, partitioning a fixed amount of work among too many threads gives each thread too little work Second, having too many threads running incurs overhead in the way they share finite processing resources

25 When designing applications that require multiple threads, it is advisable to strategize the detection of possible deadlocks Deadlocks will occur when a given thread is waiting for another thread to finish, while that thread is waiting for the previous one to complete These deadlocks must be avoided, or resolved when they occur

26

27 The most common thread communication between threads occurs between the UI thread and background threads The UI thread offloads long tasks by sending data messages to be processed on background threads Multithreaded applications should follow an efficient message passing mechanism

28 6.9 Materials and Functionality With the release of Lollipop new visual enhancement features were added to the platform and given the name Material Design A specific feature that stood out was fluid animations Surfaces and edges of material provide visual cues The use of familiar tactile attributes helps users quickly comprehend how to maneuver

29 Applying material design to an application requires the android:Theme attribute in AndroidManifest.xml to be set to Material This specification provides a collection of default animations for touch feedback and activity transitions

30 6.10 Async Tasks In general, when performing parallel tasks running longer than a few seconds, it is best to use Java threads rather than the UI thread As an alternate solution, Android provides an AsyncTask class as a convenient way to execute work units in parallel. The AsyncTask class is similar to a thread in that it allows background work to execute outside the UI thread

31 AsyncTask is designed to be a helper class for Thread and Handler and does not constitute a generic threading mechanism AsyncTask operations should not be used for long running work

32 AsyncTask is an abstract class that is designed to work with the UI An asynchronous process is defined by the following four steps, each implemented as a callback method: onPreExecute(): doInBackground(): onProgressUpdate(): onPostExecute():


Download ppt "CHAPTER 6 Threads, Handlers, and Programmatic Movement."

Similar presentations


Ads by Google