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 – Java Edition

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

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

Table of Contents (88) 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 Overview of Android View Binding 12. Understanding Android Application and Activity Lifecycles 13. Handling Android Activity State Changes 14. Android Activity State Changes by Example 15. Saving and Restoring the State of an Android Activity 16. Understanding Android Views, View Groups and Layouts 17. A Guide to the Android Studio Layout Editor Tool 18. A Guide to the Android ConstraintLayout 19. A Guide to using ConstraintLayout in Android Studio 20. Working with ConstraintLayout Chains and Ratios in Android Studio 21. An Android Studio Layout Editor ConstraintLayout Tutorial 22. Manual XML Layout Design in Android Studio 23. Managing Constraints using Constraint Sets 24. An Android ConstraintSet Tutorial 25. A Guide to using Apply Changes in Android Studio 26. An Overview and Example of Android Event Handling 27. Android Touch and Multi-touch Event Handling 28. Detecting Common Gestures using the Android Gesture Detector Class 29. Implementing Custom Gesture and Pinch Recognition on Android 30. An Introduction to Android Fragments 31. Using Fragments in Android Studio - An Example 32. Modern Android App Architecture with Jetpack 33. An Android Jetpack ViewModel Tutorial 34. An Android Jetpack LiveData Tutorial 35. An Overview of Android Jetpack Data Binding 36. An Android Jetpack Data Binding Tutorial 37. An Android ViewModel Saved State Tutorial 38. Working with Android Lifecycle-Aware Components 39. An Android Jetpack Lifecycle Awareness Tutorial 40. An Overview of the Navigation Architecture Component 41. An Android Jetpack Navigation Component Tutorial 42. Creating and Managing Overflow Menus on Android 43. An Introduction to MotionLayout 44. An Android MotionLayout Editor Tutorial 45. A MotionLayout KeyCycle Tutorial 46. Working with the Floating Action Button and Snackbar 47. Creating a Tabbed Interface using the TabLayout Component 48. Working with the RecyclerView and CardView Widgets 49. An Android RecyclerView and CardView Tutorial 50. A Layout Editor Sample Data Tutorial 51. Working with the AppBar and Collapsing Toolbar Layouts 52. An Android Studio Master/Detail Flow Tutorial 53. An Overview of Android Intents 54. Android Explicit Intents – A Worked Example 55. Android Implicit Intents – A Worked Example 56. Android Broadcast Intents and Broadcast Receivers 57. A Basic Overview of Threads and AsyncTasks 58. An Overview of Android Started and Bound Services 59. Implementing an Android Started Service – A Worked Example 60. Android Local Bound Services – A Worked Example 61. Android Remote Bound Services – A Worked Example 62. An Android Notifications Tutorial 63. An Android Direct Reply Notification Tutorial 64. Foldable Devices and Multi-Window Support 65. An Overview of Android SQLite Databases 66. The Android Room Persistence Library 67. An Android TableLayout and TableRow Tutorial 68. An Android Room Database and Repository Tutorial 69. Accessing Cloud Storage using the Android Storage Access Framework 70. An Android Storage Access Framework Example 71. Video Playback on Android using the VideoView and MediaController Classes 72. Android Picture-in-Picture Mode 73. An Android Picture-in-Picture Tutorial 74. Making Runtime Permission Requests in Android 75. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 76. Working with the Google Maps Android API in Android Studio 77. Printing with the Android Printing Framework 78. An Android HTML and Web Content Printing Example 79. A Guide to Android Custom Document Printing 80. An Introduction to Android App Links 81. An Android Studio App Links Tutorial 82. A Guide to the Android Studio Profiler 83. An Android Biometric Authentication Tutorial 84. Creating, Testing and Uploading an Android App Bundle 85. An Overview of Android Dynamic Feature Modules 86. An Android Studio Dynamic Feature Tutorial 87. An Overview of Gradle in Android Studio Index

39. An Android Jetpack Lifecycle Awareness Tutorial

The previous chapter provided an overview of lifecycle awareness and outlined the key classes and interfaces that make this possible within an Android app project. This chapter will build on this knowledge base by building an Android Studio project designed to highlight lifecycle awareness in action.

39.1 Creating the Example Lifecycle Project

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

Enter LifecycleDemo into the Name field and specify com.ebookfrenzy.lifecycledemo 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 Java.

39.2 Creating a Lifecycle Observer

As previously discussed, activities and fragments already implement the LifecycleOwner interface and are ready to be observed by other objects. To see this in practice, the next step in this tutorial is to add a new class to the project that will be able to observe the MainFragment instance.

To add the new class, right-click on app -> java -> com.ebookfrenzy.lifecycledemo in the Project tool window and select New -> Java Class... from the resulting menu. In the New Class dialog, name the class DemoObserver and press the keyboard Return key to create the DemoObserver.java file. The new file should automatically open in the editor where it will read as follows:

package com.ebookfrenzy.lifecycledemo;

 

public class DemoObserver {

}

Remaining in the editor, modify the class file to declare that it will be implementing the LifecycleObserver interface:

package com.ebookfrenzy.lifecycledemo;

 

import androidx...

39.3 Adding the Observer

Observers are added to lifecycle owners via calls to the addObserver() method of the owner’s Lifecycle object, a reference to which is obtained via a call to the getLifecycle() method. Edit the MainFragment.java class file and add code to the onActivityCreated() method to add the observer:

.

.

import com.ebookfrenzy.lifecycledemo.DemoObserver;

.

.

@Override

public void onActivityCreated(@Nullable Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    mViewModel = new ViewModelProvider(this).get(MainViewModel.class);

 

    getLifecycle().addObserver(new DemoObserver());

}

With the observer class created and added to the lifecycle owner’s Lifecycle object, the app is ready to be tested.

39.4 Testing the Observer

Since the DemoObserver class outputs diagnostic information to the Logcat console, it will be easier to see the output if a filter is configured to display only the DemoObserver messages. Using the steps outlined previously in “Android Activity State Changes by Example”, configure a filter for messages associated with the DemoObserver tag before running the app on a device or emulator.

On successful launch of the app, the Logcat output should indicate the following lifecycle state changes and events:

onCreate

CREATED

onStart

STARTED

onResume

RESUMED

With the app still running, perform a device rotation to trigger the destruction and recreation of the fragment, generating the following additional output:

onPause

STARTED

onStop

CREATED

onDestroy

DESTROYED

onCreate

CREATED

onStart

STARTED

onResume

RESUMED

Before moving to the next section in this chapter, take some time to compare the...

39.5 Creating a Lifecycle Owner

The final task in this chapter is to create a custom lifecycle owner class and demonstrate how to trigger events and modify the lifecycle state from within that class.

Add a new class by right-clicking on the app -> java -> com.ebookfrenzy.lifecycledemo entry in the Project tool window and selecting the New -> Java Class... menu option. Name the class DemoOwner in the Create Class dialog before tapping the keyboard Return key. With the new DemoOwner.java file loaded into the code editor, modify it as follows:

package com.ebookfrenzy.lifecycledemo;

 

import androidx.lifecycle.Lifecycle;

import androidx.lifecycle.LifecycleOwner;

import androidx.lifecycle.LifecycleRegistry;

 

import org.jetbrains.annotations.NotNull;

 

public class DemoOwner implements LifecycleOwner {

}

The class is going to need a LifecycleRegistry instance initialized with a reference to itself, and a getLifecycle() method configured...

39.6 Testing the Custom Lifecycle Owner

Build and run the app one final time, refer to the Logcat tool window and confirm that the observer detected the create, start and stop lifecycle events in the following order:

onCreate

CREATED

onStart

STARTED

onStop

CREATED

Note that the “created” state changes were triggered even though code was not added to the DemoOwner class to do this manually. In fact, these were triggered automatically both when the owner instance was first created and subsequently when the ON_STOP event was handled.

39.7 Summary

This chapter has provided a practical demonstration of the steps involved in implementing lifecycle awareness within an Android app. This included the creation of a lifecycle observer and the design and implementation of a basic lifecycle owner class.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021 Publisher: Packt ISBN-13: 9781801815161
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 €14.99/month. Cancel anytime}