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.1 Development Essentials – Kotlin Edition

You're reading from  Android Studio 4.1 Development Essentials – Kotlin Edition

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

Table of Contents (95) 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 Master/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. A Basic Overview of Threads and AsyncTasks 64. An Introduction to Kotlin Coroutines 65. An Android Kotlin Coroutines Tutorial 66. An Overview of Android Started and Bound Services 67. Implementing an Android Started Service – A Worked Example 68. Android Local Bound Services – A Worked Example 69. Android Remote Bound Services – A Worked Example 70. An Android Notifications Tutorial 71. An Android Direct Reply Notification Tutorial 72. Foldable Devices and Multi-Window Support 73. An Overview of Android SQLite Databases 74. The Android Room Persistence Library 75. An Android TableLayout and TableRow Tutorial 76. An Android Room Database and Repository Tutorial 77. Accessing Cloud Storage using the Android Storage Access Framework 78. An Android Storage Access Framework Example 79. Video Playback on Android using the VideoView and MediaController Classes 80. Android Picture-in-Picture Mode 81. An Android Picture-in-Picture Tutorial 82. Making Runtime Permission Requests in Android 83. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 84. Printing with the Android Printing Framework 85. An Android HTML and Web Content Printing Example 86. A Guide to Android Custom Document Printing 87. An Introduction to Android App Links 88. An Android Studio App Links Tutorial 89. A Guide to the Android Studio Profiler 90. An Android Biometric Authentication Tutorial 91. Creating, Testing and Uploading an Android App Bundle 92. An Overview of Android Dynamic Feature Modules 93. An Android Studio Dynamic Feature Tutorial 94. An Overview of Gradle in Android Studio Index

65. An Android Kotlin Coroutines Tutorial

The previous chapter introduced the key concepts of performing asynchronous tasks within Android apps using Kotlin coroutines. This chapter will build on this knowledge to create an example app that launches thousands of coroutines at the touch of a button.

65.1 Creating the Coroutine Example Application

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Empty Activity template before clicking on the Next button.

Enter CoroutineDemo into the Name field and specify com.ebookfrenzy.coroutinedemo as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Kotlin.

Locate and open the app -> Gradle Scripts - > build.gradle (Module: CoroutineDemo.app) file in the project tool window and modify the plugins section so that reads as follows before clicking the Sync Now link in the toolbar to commit the change:

plugins {

    id 'com.android.application

    id 'kotlin-android'

    id 'kotlin-android-extensions'

}

65.2 Adding Coroutine Support to the Project

The current version of Android Studio does not automatically include support for coroutines in newly created projects. Before proceeding, therefore, edit the Gradle Scripts -> build.gradle (Module: CoroutineDemo.app) file and add the following lines to the dependencies section (noting, as always, that newer versions of the libraries may be available):

dependencies {

.

.

    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'

    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'

.

.

}

After making the change, click on the Sync Now link at the top of the editor panel to commit the changes.

65.3 Designing the User Interface

The user interface will consist of a button to launch coroutines together with a Seekbar to specify how many coroutines are to be launched asynchronously each time the button is clicked. As the coroutines execute, a TextView will update when individual coroutines start and end.

Begin by loading the activity_main.xml layout file and add the Button, TextView and SeekBar objects so that the layout resembles that shown in Figure 65-1:

Figure 65-1

To implement the layout constraints shown above begin by clearing all constraints on the layout using the toolbar button. Shift-click on the four objects so that all are selected, right-click over the top-most TextView and select the Center -> Horizontally menu option. Right-click once again, this time selecting the Chains -> Create Vertical Chain option.

Select the SeekBar and change the layout_width property to 0dp (match_constraints) before adding a 24dp margin on the left and right hand...

65.4 Implementing the SeekBar

The SeekBar controls the number of asynchronous coroutines, ranging from 1 to 2000, that are launched each time the button is clicked. Remaining within the activity_main.xml file, select the SeekBar and use the Attributes tool window to change the max property to 2000. Next, edit the MainActivity.kt file, add a variable in which to store the current slider setting and modify the onCreate() method to add a SeekBar listener:

.

.

import android.widget.SeekBar

import kotlinx.android.synthetic.main.activity_main.*

.

.

class MainActivity : AppCompatActivity() {

 

    private var count: Int = 1

 

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

 

       ...

65.5 Adding the Suspend Function

When the user taps the button the app will need to launch the number of coroutines selected in the SeekBar. The launchCoroutines() onClick method will achieve this using the coroutine launch builder to execute a suspend function. Since the suspend function will return a status string to be displayed on the statusText TextView object, it will need to be implemented using the async builder. All of these actions will need to be performed within a coroutine scope which also needs to be declared. Within the MainActivity.kt file make the following changes:

.

.

import kotlinx.coroutines.*

.

.

class MainActivity : AppCompatActivity() {

    private val coroutineScope = CoroutineScope(Dispatchers.Main)

.

.

   suspend fun performTask(tasknumber: Int): Deferred<String> =

        coroutineScope.async(Dispatchers.Main) {

     ...

65.6 Implementing the launchCoroutines Method

The final task before testing the app is to add the launchCoroutines() method which is called when the Button object is clicked. This method should be added to the MainActivity.kt file as follows:

.

.

import android.view.View

.

.

    fun launchCoroutines(view: View) {

 

        (1..count).forEach {

            statusText.text = "Started Coroutine ${it}"

            coroutineScope.launch(Dispatchers.Main) {

                statusText.text = performTask(it).await()

            }

        }

    }

.

.

The...

65.7 Testing the App

Build and run the app on a device or emulator and move the SeekBar to a low number (for example 10) before tapping the launch button. The status text will update each time a coroutine is launched until the maximum is reached. After each coroutine completes the 5 second delay the status text will update until all 10 have completed (in practice these status updates will happen so quickly it will be difficult to see the status changes).

Repeat the process with the SeekBar set to 2000, this time sliding the seekbar back and forth as the coroutines run to verify that the main thread is still running and has not been blocked.

Finally, with the Logcat panel displayed, set the SeekBar to 2000 and click on the launch button repeatedly. After about 15 clicks the Logcat panel will begin displaying messages similar to the following:

I/Choreographer: Skipped 52 frames! The application may be doing too much work on its main thread.

Although the app continues to...

65.8 Summary

Building on the information covered in “An Introduction to Kotlin Coroutines”, this chapter has stepped through the creation of an example app that demonstrates the use of Kotlin coroutines within an Android app. The example demonstrated the use of the Main dispatcher to launch thousands of asynchronous coroutines, including returning results.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Kotlin Edition
Published in: May 2021 Publisher: Packt ISBN-13: 9781801815987
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}