Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android Studio 4.2 Development Essentials - Kotlin Edition

You're reading from  Android Studio 4.2 Development Essentials - Kotlin Edition

Product type Book
Published in Aug 2021
Publisher Packt
ISBN-13 9781803231549
Pages 804 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (94) Chapters

1. Introduction 2. Setting up an Android Studio Development Environment 3. Creating an Example Android App in Android Studio 4. Creating an Android Virtual Device (AVD) in Android Studio 5. Using and Configuring the Android Studio AVD Emulator 6. A Tour of the Android Studio User Interface 7. Testing Android Studio Apps on a Physical Android Device 8. The Basics of the Android Studio Code Editor 9. An Overview of the Android Architecture 10. The Anatomy of an Android Application 11. An Introduction to Kotlin 12. Kotlin Data Types,Variables and Nullability 13. Kotlin Operators and Expressions 14. Kotlin Flow Control 15. An Overview of Kotlin Functions and Lambdas 16. The Basics of Object Oriented Programming in Kotlin 17. An Introduction to Kotlin Inheritance and Subclassing 18. An Overview of Android View Binding 19. Understanding Android Application and Activity Lifecycles 20. Handling Android Activity State Changes 21. Android Activity State Changes by Example 22. Saving and Restoring the State of an Android Activity 23. Understanding Android Views, View Groups and Layouts 24. A Guide to the Android Studio Layout Editor Tool 25. A Guide to the Android ConstraintLayout 26. A Guide to Using ConstraintLayout in Android Studio 27. Working with ConstraintLayout Chains and Ratios in Android Studio 28. An Android Studio Layout Editor ConstraintLayout Tutorial 29. Manual XML Layout Design in Android Studio 30. Managing Constraints using Constraint Sets 31. An Android ConstraintSet Tutorial 32. A Guide to using Apply Changes in Android Studio 33. An Overview and Example of Android Event Handling 34. Android Touch and Multi-touch Event Handling 35. Detecting Common Gestures Using the Android Gesture Detector Class 36. Implementing Custom Gesture and Pinch Recognition on Android 37. An Introduction to Android Fragments 38. Using Fragments in Android Studio - An Example 39. Modern Android App Architecture with Jetpack 40. An Android Jetpack ViewModel Tutorial 41. An Android Jetpack LiveData Tutorial 42. An Overview of Android Jetpack Data Binding 43. An Android Jetpack Data Binding Tutorial 44. An Android ViewModel Saved State Tutorial 45. Working with Android Lifecycle-Aware Components 46. An Android Jetpack Lifecycle Awareness Tutorial 47. An Overview of the Navigation Architecture Component 48. An Android Jetpack Navigation Component Tutorial 49. An Introduction to MotionLayout 50. An Android MotionLayout Editor Tutorial 51. A MotionLayout KeyCycle Tutorial 52. Working with the Floating Action Button and Snackbar 53. Creating a Tabbed Interface using the TabLayout Component 54. Working with the RecyclerView and CardView Widgets 55. An Android RecyclerView and CardView Tutorial 56. A Layout Editor Sample Data Tutorial 57. Working with the AppBar and Collapsing Toolbar Layouts 58. An Android Studio Primary/Detail Flow Tutorial 59. An Overview of Android Intents 60. Android Explicit Intents – A Worked Example 61. Android Implicit Intents – A Worked Example 62. Android Broadcast Intents and Broadcast Receivers 63. An Introduction to Kotlin Coroutines 64. An Android Kotlin Coroutines Tutorial 65. An Overview of Android Services 66. Implementing an Android Started Service – A Worked Example 67. Android Local Bound Services – A Worked Example 68. Android Remote Bound Services – A Worked Example 69. An Android Notifications Tutorial 70. An Android Direct Reply Notification Tutorial 71. Foldable Devices and Multi-Window Support 72. An Overview of Android SQLite Databases 73. The Android Room Persistence Library 74. An Android TableLayout and TableRow Tutorial 75. An Android Room Database and Repository Tutorial 76. Accessing Cloud Storage using the Android Storage Access Framework 77. An Android Storage Access Framework Example 78. Video Playback on Android using the VideoView and MediaController Classes 79. Android Picture-in-Picture Mode 80. An Android Picture-in-Picture Tutorial 81. Making Runtime Permission Requests in Android 82. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 83. Printing with the Android Printing Framework 84. An Android HTML and Web Content Printing Example 85. A Guide to Android Custom Document Printing 86. An Introduction to Android App Links 87. An Android Studio App Links Tutorial 88. A Guide to the Android Studio Profiler 89. An Android Biometric Authentication Tutorial 90. Creating, Testing and Uploading an Android App Bundle 91. An Overview of Android Dynamic Feature Modules 92. An Android Studio Dynamic Feature Tutorial 93. An Overview of Gradle in Android Studio Index

65. An Overview of Android Services

The Android Service class is designed specifically to allow applications to initiate and perform background tasks. Unlike broadcast receivers, which are intended to perform a task quickly and then exit, services are designed to perform tasks that take a long time to complete (such as downloading a file over an internet connection or streaming music to the user) but do not require a user interface.

In this chapter, an overview of the different types of services available will be covered, including started services, bound services and intent services. Once these basics have been covered, subsequent chapters will work through a number of examples of services in action.

65.1 Started Services

Started services are launched by other application components (such as an activity or even a broadcast receiver) and potentially run indefinitely in the background until the service is stopped, or is destroyed by the Android runtime system in order to free up resources. A service will continue to run if the application that started it is no longer in the foreground, and even in the event that the component that originally started the service is destroyed.

By default, a service will run within the same main thread as the application process from which it was launched (referred to as a local service). It is important, therefore, that any CPU intensive tasks be performed in a new thread within the service. Instructing a service to run within a separate process (and therefore known as a remote service) requires a configuration change within the manifest file.

Unless a service is specifically configured to be private (once again via a setting in the manifest...

65.2 Intent Service

As previously outlined, services run by default within the same main thread as the component from which they are launched. As such, any CPU intensive tasks that need to be performed by the service should take place within a new thread, thereby avoiding impacting the performance of the calling application.

The JobIntentService class is a convenience class (subclassed from the Service class) that sets up a worker thread for handling background tasks and handles each request in an asynchronous manner. Once the service has handled all queued requests, it simply exits. All that is required when using the JobIntentService class is that the onHandleWork() method be implemented containing the code to be executed for each request.

For services that do not require synchronous processing of requests, JobIntentService is the recommended option. Services requiring synchronous handling of requests will, however, need to subclass from the Service class and manually implement...

65.3 Bound Service

A bound service is similar to a started service with the exception that a started service does not generally return results or permit interaction with the component that launched it. A bound service, on the other hand, allows the launching component to interact with, and receive results from, the service. Through the implementation of interprocess communication (IPC), this interaction can also take place across process boundaries. An activity might, for example, start a service to handle audio playback. The activity will, in all probability, include a user interface providing controls to the user for the purpose of pausing playback or skipping to the next track. Similarly, the service will quite likely need to communicate information to the calling activity to indicate that the current audio track has completed and to provide details of the next track that is about to start playing.

A component (also referred to in this context as a client) starts and binds to...

65.4 The Anatomy of a Service

A service must, as has already been mentioned, be created as a subclass of the Android Service class (more specifically android.app.Service) or a sub-class thereof (such as android.app.IntentService). As part of the subclassing procedure, one or more of the following superclass callback methods must be overridden, depending on the exact nature of the service being created:

onStartCommand() – This is the method that is called when the service is started by another component via a call to the startService() method. This method does not need to be implemented for bound services.

onBind() – Called when a component binds to the service via a call to the bindService() method. When implementing a bound service, this method must return an IBinder object facilitating communication with the client. In the case of started services, this method must be implemented to return a NULL value.

onCreate() – Intended...

65.5 Controlling Destroyed Service Restart Options

The onStartCommand() callback method is required to return an integer value to define what should happen with regard to the service in the event that it is destroyed by the Android runtime system. Possible return values for these methods are as follows:

START_NOT_STICKY – Indicates to the system that the service should not be restarted in the event that it is destroyed unless there are pending intents awaiting delivery.

START_STICKY – Indicates that the service should be restarted as soon as possible after it has been destroyed if the destruction occurred after the onStartCommand() method returned. In the event that no pending intents are waiting to be delivered, the onStartCommand() callback method is called with a NULL intent value. The intent being processed at the time that the service was destroyed is discarded.

START_REDELIVER_INTENT – Indicates that, if the service was destroyed...

65.6 Declaring a Service in the Manifest File

In order for a service to be useable, it must first be declared within a manifest file. This involves embedding an appropriately configured <service> element into an existing <application> entry. At a minimum, the <service> element must contain a property declaring the class name of the service as illustrated in the following XML fragment:

.

.

    <application

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name" >

        <activity

            android:label="@string/app_name"

            android:name=".MainActivity" >

      &...

65.7 Starting a Service Running on System Startup

Given the background nature of services, it is not uncommon for a service to need to be started when an Android-based system first boots up. This can be achieved by creating a broadcast receiver with an intent filter configured to listen for the system android.intent.action.BOOT_COMPLETED intent. When such an intent is detected, the broadcast receiver would simply invoke the necessary service and then return. Note that, in order to function, such a broadcast receiver will need to request the android.permission.RECEIVE_BOOT_COMPLETED permission.

65.8 Summary

Android services are a powerful mechanism that allows applications to perform tasks in the background. A service, once launched, will continue to run regardless of whether the calling application is the foreground task or not, and even in the event that the component that initiated the service is destroyed.

Services are subclassed from the Android Service class and fall into the category of either started services or bound services. Started services run until they are stopped or destroyed and do not inherently provide a mechanism for interaction or data exchange with other components. Bound services, on the other hand, provide a communication interface to other client components and generally run until the last client unbinds from the service.

By default, services run locally within the same process and main thread as the calling application. A new thread should, therefore, be created within the service for the purpose of handling CPU intensive tasks. Remote services...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.2 Development Essentials - Kotlin Edition
Published in: Aug 2021 Publisher: Packt ISBN-13: 9781803231549
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime}