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

83. An Android Biometric Authentication Tutorial

Touch sensors are now built into many Android devices to identify the user and provide access to both the device and application functionality such as in-app payment options using fingerprint recognition. Fingerprint recognition is, of course, just one of a number of different authentication methods including passwords, PIN numbers and, more recently, facial recognition.

Although only a few Android devices currently on the market provide facial recognition, it is likely that this will become more common in the near future. In recognition of this, Google has begun to transition away from what was a fingerprint-centric approach to adding authentication to apps to a less specific approach that is referred to as biometric authentication. In the initial release of Android 8, these biometric features only cover fingerprint authentication but this will change in future releases and updates of the Android operating system and SDK.

This...

83.1 An Overview of Biometric Authentication

The key biometric authentication component is the BiometricPrompt class. This class performs much of the work that previously had to be performed by writing code in earlier Android versions, including displaying a standard dialog to guide the user through the authentication process, performing the authentication and reporting the results to the app. The class also handles excessive failed authentication attempts and enforces a timeout before the user can try again.

The BiometricPrompt class includes a companion Builder class that can be used to configure and create BiometricPrompt instances, including defining the text that is to appear within the biometric authentication dialog and the customization of the cancel button (also referred to as the negative button) that appears in the dialog.

The BiometricPrompt instance is also assigned a set of authentication callbacks that will be called to provide the app with the results of an authentication...

83.2 Creating the Biometric Authentication Project

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 BiometricDemo into the Name field and specify com.ebookfrenzy.biometricdemo as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 29: Android 9.0 (Pie) and the Language menu to Java.

83.3 Configuring Device Fingerprint Authentication

Fingerprint authentication is only available on devices containing a touch sensor and on which the appropriate configuration steps have been taken to secure the device and enroll at least one fingerprint. For steps on configuring an emulator session to test fingerprint authentication, refer to the chapter entitled “Using and Configuring the Android Studio AVD Emulator”.

To configure fingerprint authentication on a physical device begin by opening the Settings app and selecting the Security option. Within the Security settings screen, select the Fingerprint option. On the resulting information screen click on the Next button to proceed to the Fingerprint setup screen. Before fingerprint security can be enabled a backup screen unlocking method (such as a PIN number) must be configured. If the lock screen is not already secured, follow the steps to configure either PIN, pattern or password security.

With the lock screen...

83.4 Adding the Biometric Permission to the Manifest File

Biometric authentication requires that the app request the USE_BIOMETRIC permission within the project manifest file. Within the Android Studio Project tool window locate and edit the app -> manifests -> AndroidManifest.xml file to add the permission request as follows:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.ebookfrenzy.biometricdemo">

 

    <uses-permission

        android:name="android.permission.USE_BIOMETRIC" />

.

.

83.5 Designing the User Interface

In the interests of keeping the example as simple as possible, the only visual element within the user interface will be a Button view. Locate and select the activity_main.xml layout resource file to load it into the Layout Editor tool.

Delete the sample TextView object, drag and drop a Button object from the Common category of the palette and position it in the center of the layout canvas. Using the Attributes tool window, change the text property on the button to “Authenticate” and extract the string to a resource. Finally, configure the onClick property to call a method named authenticateUser.

On completion of the above steps the layout should match that shown in Figure 83-2:

Figure 83-2

83.6 Adding a Toast Convenience Method

At various points throughout the code in this example the app will be designed to display information to the user via Toast messages. Rather than repeat the same Toast code multiple times, a convenience method named notifyUser() will be added to the main activity. This method will accept a single String value and display it to the user in the form of a Toast message. Edit the MainActivity.java file now and add this method as follows:

.

.

import android.widget.Toast;

.

.

    private void notifyUser(String message) {

        Toast.makeText(this,

                message,

                Toast.LENGTH_LONG).show();

    }

.

.

83.7 Checking the Security Settings

Earlier in this chapter steps were taken to configure the lock screen and register fingerprints on the device or emulator on which the app is going to be tested. It is important, however, to include defensive code in the app to make sure that these requirements have been met before attempting to seek fingerprint authentication. These steps will be performed within the onCreate method residing in the MainActivity.java file, making use of the Keyguard and PackageManager manager services. Note that code has also been added to verify that the USE_BIOMETRIC permission has been configured for the app:

package com.ebookfrenzy.biometricdemo;

 

import androidx.appcompat.app.AppCompatActivity;

import androidx.core.app.ActivityCompat;

 

import android.widget.Toast;

import android.Manifest;

import android.content.pm.PackageManager;

 

import android.app.KeyguardManager;

 

public class MainActivity extends...

83.8 Configuring the Authentication Callbacks

When the biometric prompt dialog is configured, it will need to be assigned a set of authentication callback methods that can be called to notify the app of the success or failure of the authentication process. These methods need to be wrapped in a BiometricPrompt.AuthenticationCallback class instance. Remaining in the MainActivity.java file, add a method to create and return an instance of this class with the appropriate methods implemented:

.

.

import android.hardware.biometrics.BiometricPrompt;

.

.

    private BiometricPrompt.AuthenticationCallback getAuthenticationCallback() {

 

        return new BiometricPrompt.AuthenticationCallback() {

            @Override

            public void onAuthenticationError(int errorCode,...

83.9 Adding the CancellationSignal

Once initiated, the biometric authentication process is performed independently of the app. To provide the app with a way to cancel the operation, an instance of the CancellationSignal class is created and passed to the biometric authentication process. This CancellationSignal instance can then be used to cancel the process if necessary. The cancellation signal instance may be configured with a listener which will be called when the cancellation is completed. Add a new method to the activity class to configure and return a CancellationSignal object as follows:

.

.

import android.os.CancellationSignal;

.

.

   private CancellationSignal cancellationSignal;

.

.

    private CancellationSignal getCancellationSignal() {

 

        cancellationSignal = new CancellationSignal();

        cancellationSignal...

83.10 Starting the Biometric Prompt

All that remains is to add code to the authenticateUser() method to create and configure a BiometricPrompt instance and initiate the authentication. Add the authenticateUser() method as follows:

.

.

import android.view.View;

import android.content.DialogInterface;

.

.

public void authenticateUser(View view) {

    BiometricPrompt biometricPrompt = new BiometricPrompt.Builder(this)

            .setTitle("Biometric Demo")

            .setSubtitle("Authentication is required to continue")

            .setDescription("This app uses biometric authentication to protect your data.")

            .setNegativeButton("Cancel", this...

83.11 Testing the Project

With the project now complete, run the app on a physical Android device or emulator session and click on the Authenticate button to display the BiometricPrompt dialog as shown in Figure 83-3:

Figure 83-3

Once running, either touch the fingerprint sensor or use the extended controls panel within the emulator to simulate a fingerprint touch as outlined in the chapter entitled “Using and Configuring the Android Studio AVD Emulator”. Assuming a registered fingerprint is detected the prompt dialog will return to the main activity where the toast message from the successful authentication callback method will appear.

Click the Authenticate button once again, this time using an unregistered fingerprint to attempt the authentication. This time the biometric prompt dialog will indicate that the fingerprint was not recognized:

Figure 83-4

Verify that the error handling callback is working by clicking on the activity outside of the...

83.12 Summary

This chapter has outlined how to integrate biometric authentication into an Android app project. This involves the use of the BiometricPrompt class which, once configured with appropriate message text and callbacks, automatically handles most of the authentication process.

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}