Android Development

Android Development

Google’s latest experiment lets you jam on a keyboard with an AI partner

0

If you are a musician, or just someone who wants to make some music in your spare time, it’s natural to want to play and jam out with a friend. However, you might not have anyone around when that time comes. The Google Creative Lab team says it’s ready to help with its latest experiment called A.I. Duet.

See also:

Is Google’s Fuchsia OS the key to merge Android and Chrome OS or not?

1 day ago

The basis for this experiment is Magenta, an open-source project by Google that was first announced in May 2016. It’s designed to use the company’s TensorFlow machine learning software library to help people create art and music. In this case, A.I. Duet is designed around a virtual keyboard. When you start playing a few notes, the computer is supposed to respond to it with the appropriate melody.

You can go ahead and check out A.I. Duet right now on Google’s website. You can simply tap on the virtual keys to get started, and you can use a touchscreen to hit those keys if you have a smartphone or tablet. If you are on a PC, you can use your computer keyboard buttons. Finally, you can hook up a MIDI-based keyboard to your PC to get the full effect.

Google has also posted the code created for A.I. Duet as an open-source project on GitHub, in case you want to make it better. The company says that it hope this will allow others to “extend the functionality of A.I. Duet to address even more research questions surrounding creativity and computation”. While this is certainly a small scale effort, it also shows that Google wants to help expand the reach of artificial intelligence beyond just answering questions, like we see with Google Assistant and other voice-based digital AI services.

If you do play music, what is your opinion on A.I. Duet? Let us know your impressions in the comments!

Check out A.I. Duet

 

IBM helped create an Android weather app that sends alerts without a cell network

Many people in developing countries own smartphones, but don’t always have access to reliable wireless connections. That’s a problem when they may just need them to get alerts for emergencies. This week, IBM announced it has developed a new version of the Weather Channel Android app for those markets, what makes it so special? It can send emergency alerts to smartphones without the need for a cellular connection.

See also:

Best weather apps and weather widgets for Android

January 15, 2017

You may not be aware, but IBM actually acquired The Weather Company, the home of The Weather Channel cable TV network and the creators of the Weather Channel app, in 2016. Since then, the company claims it has made extra efforts to extend its weather forecasts and alerts to more mobile users worldwide. One of of those efforts is the use of Mesh Network Alerts technology to sent notifications to smartphones in certain markets.

IBM said that by using these mesh networks, emergency alerts can be sent to smartphones on its Weather Channel app via peer-to-peer connections, instead of a cellular network:

Usually, a government-issued message is broadcast via cell tower to all devices within its range. When that network goes down, however, so does the ability to send alerts. Peer-to-peer technology converts mobile devices into links within the mesh network, allowing devices to “talk” directly to each other without using cell tower infrastructure. Each smartphone becomes a node that stores the message and passes it to the next nearest device, creating a daisy chain to reach more devices and remove the need for a cellular network.

This technology does not turn smartphones into mobile hotspots, according to IBM, because that causes too much battery drain. It still uses phones that connect with Bluetooth or WiFi to send those alerts out.

The new version of the Android Weather Channel app that supports these mesh network alerts is already available to download in 42 countries from the Google Play Store. In addition, IBM has worked to cut down the download file size of this app to just 3.2 MB, while still providing full weather data, forecasts, and notifications, along with the ability to store weather data offline for up to 24 hours. The app is also been designed to launch and load quickly even on slower 3G and 2G cellular connections.

The ability for smartphones to still work even when solid cellular connections are not available seems to be a growing trend. Just today, the new chairman of the Federal Communications Commission, Ajit Pai, said he would like to see more smartphone companies activate the often hidden FM radio hardware inside. While he doesn’t want the US government to mandate that kind of feature in phones, Pai said it would let consumers get emergency alerts if their local cell tower was not working.

Would you like more apps and features on your phone that worked even without a cellular connection for emergencies? Let us know where you stand in the comments!

It’s the end for Android 2.3 Gingerbread with Google Play Services 10.2

If they haven’t done so already on their own, Android developers can now no longer use Google Play Services for any apps that support Android 2.3 Gingerbread. The company previously said this would happen in early 2017, and now the change notes for Google Play Services 10.2 that went live this week confirm it is the first without support for Gingerbread.

See also:

IoT-based Android Things Developer Preview 2 released

7 days ago

Google Play Services offers developers a set of software libraries so they can add features to their Android apps. For the few remaining people who might still be using a Gingerbread-based phone (the OS was launched in 2010), this new move doesn’t mean your phone will stop working, but any apps that you have installed will likely not be updated anymore. The end of Gingerbread support for Google Play Services is also extended to the company’s Firebase client libraries for Android.

While Gingerbread support may be gone, Google Play Services 10.2 does add a number of new features for Android app developers to use. If they are using the Google Fit tools in their apps, they can now include features to monitor even more health data, including blood pressure, blood glucose, oxygen saturation, body position, body temperature, and reproductive health data. Apps that use the Google Maps tools can now include custom styling for polylines and for the outlines of polygons and circles, too.

Also, the Google Sign-in API can now be used by Android game developers, which should make server-side authentication easier for those apps. There are also quite a few improvements for the Ads tools, including new support for video assets to Native Advanced content ads.

Obviously, most of these changes are for app developers only, but they will likely lead to better Android apps in the long run for consumers, if they are not still rocking a Gingerbread-based phone.  Are you still holding onto a device with Gingerbread installed? Probably not, but if so, let us know in the comments.

This Weekend Only: Save Big on Coding Courses (70% off everything!)

The AAPicks team writes about things we think you’ll like, and we may see a share of revenue from any purchases made through affiliate links.

Shutterstock

It’s Autodidact Weekend over at Tech Deals, and in celebration the company is letting Android Authority readers in on a pretty sweet offer.

From now through Sunday, you can save massively on some of the hottest online courses on the web.

If your New Year’s Resolution involved committing yourself to learning how to code, hack, or develop websites, then this is a weekend you can’t afford to miss out on!

Get 70 percent off your entire cart filled with online courses when you check out using the coupon code LEARN70.

This coupon code applies to all courses in your cart, so if you really want to save big, scoop up multiple courses at once!

Here are our favorites, but there are many more:

The Complete Android N Developer Course – Build 17 Apps

This Weekend Only: Save Big on Coding Courses (70% off everything!)

Beloved online instructor Rob Percival has crafted the second-most popular online developer course around (the most popular one is actually for iOS, and is also by Percival).

Learn how to make your own apps as you’re walked through 17 increasingly complex projects that teach you everything you need to know about developing for Android from scratch!

Check it Out!

The Complete Web Developer Course 2.0

This Weekend Only: Save Big on Coding Courses (70% off everything!)

Not surprising to see Rob Percival again on this list, now teaching you how to build websites! The internet is only going to get bigger, and companies need savvy developers to get their websites up and running.

Could be the start of a total career change!

Check it Out!

Certified White-Hat Hacker and Penetration Testing Course

This Weekend Only: Save Big on Coding Courses (70% off everything!)

In a time when many people are concerned about their jobs, there’s one field that keeps getting bigger and bigger: security experts. In fact, there aren’t enough white-hat hackers to go around, so many of these internet BAMFs are commanding salaries of upwards of $100,000.

Check it Out!

Become a Professional Python Programmer

This Weekend Only: Save Big on Coding Courses (70% off everything!)

Python is one of the most versatile languages out there, and it’s becoming increasingly popular among AI and machine learning experts.

Even if you’re not interested in that field, you can also use python for web development, data analytics, game development, or even controlling robots! Learn how today!

Check it Out!

CentOS and Red Hat Linux Certified System Administrator Course

This Weekend Only: Save Big on Coding Courses (70% off everything!)

Even if you don’t have any Linux experience, this learning kit can get you up and running to be a full systems admin. In addition to showing you the ropes, this course also preps you for the RHCSA exam, so you can get certified and start marketing yourself as an employable admin right away!

Check it Out!
The AAPicks team only spotlights legitimate, verified deals. If you have questions or concerns, please reach out at aapicks@koimoi.com.pk.

Developers can now make Android apps that can control parts of nearby Windows 10 PCs

Android may be the most used operating system for smartphones, but Microsoft still rules the PC market with its Windows OS. The company released its latest version, Windows 10, in 2015 and it is currently installed, depending on which report you believe, on over 20 percent of all PCs worldwide. The company says that over 400 million active devices are running some version of Windows 10.

See also:

The Developers Alliance finds some interesting facts about Android users

November 22, 2016

This week, Microsoft released the first version of what it calls “Project Rome”. It’s an Android app SDK that allows developers to create software that can remotely control some parts of a Windows 10 PC. Any app that uses the SDK must first log into a Microsoft account that is available on both the phone and the PC.

Once that’s done, an app with Project Rome support can scan the local network for a Windows 10 PC. When that app finds such a PC, it can then be used to launch a Windows 10 app, or launch a web site by typing in a URL.

In the future, Microsoft plans to add a way for Android apps that also come with a Windows 10 version to be directly controlled from a smartphone, rather than just launch it. For example, a user could be able to open up his Android app and launch and control a movie remotely on his Windows 10 PC via a media player. Again, this feature is coming in a future Project Rome SDK version.

This new feature is just for controlling Android apps on a Windows 10 PC, and not vice-versa. Microsoft has not revealed plans to add that kind of support, but we would hope that’s kind of a no-brainer to include in a future release. This also proves that Microsoft continues to be a company that wants to support Android development, especially since its own Windows 10 Mobile OS is currently not much of a force in the smartphone market.

The first Project Rome Android SDK version can be downloaded right now via GitHub.

Final Android Wear 2.0 SDK arrives for developers

On Wednesday, Google officially announced the release of Android Wear 2.0. Today, developers can snag the final version of the Android Wear 2.0 SDK, allowing them to prepare their older apps for the launch of the first smartwatches that will use the updated OS. LG’s Watch Sport and Watch Style are the first two devices to run version 2.0, and both will go on sale Friday, February 10.

See also:

Which smartwatches will get updated to Android Wear 2.0?

1 day ago

The new SDK includes a way for developers to add support in their apps for the many hardware additions and software improvements in Android Wear 2.0. They include Material Design-based system user interfaces and design guidelines, support for releasing Android Wear apps that can be downloaded and installed without a smartphone, and iOS support for apps. In addition, the SDK allows developers to create new types of watch faces with complications for Android Wear 2.0 that can offer features other than just telling the time.

As previously mentioned, the first two smartwatches that will be sold Friday with Android Wear 2.0 are the LG Watch Sport and LG Watch Style. At the moment, app developers will need to get one of these smartwatches to test out the use of Android Wear 2.0’s new API support for physical button locations and rotary input. However, the plan is to update the SDK at some point so that these features can be tested with an emulator app.

In addition to updating the SDK, the app quality review process will be adding two new rules for Android Wear 2.0 apps. One is that apps that just offer enhancements from previous notifications made for a phone app won’t be accepted in the new review rules. The other big change is that developers will be required to upload a watch APK that’s compatible with Android Wear 2.0.

While the two new LG watches will be the first with Android Wear 2.0, many older Android Wear devices will offer updates to the new 2.0 version over the coming weeks and months.

IoT-based Android Things Developer Preview 2 released

In December, Google first announced Android Things, its new attempt to create a better Internet of Things (IoT) operating system. Today, the company has released the second developer preview of Android Things, with a number of new additions and bug fixes.

See also:

What is Android Things? – Gary explains

4 weeks ago

Developer Preview 2 now includes support for the Intel Joule hardware platform, which Google says offers “the most computing power in our lineup to date” for Android Things-based devices. USB Audio support to the Hardware Abstraction Layer (HAL) has been included for the Intel Edison and Raspberry Pi 3 boards with this new release. Developers who use native C or C++ code for their IoT products can now continue to use it with Android Things, thanks to the newly added native access to the Peripheral API (PIO).

Google has also created sample code for the OS that shows developers how to use the TensorFlow machine learning software library on Android Things devices.  It includes demos that can access a camera on such a board so it can use  its object recognition and image classification features. The new support also adds a way speak out the results using text-to-speech (TTS) features.

Android Things seems to be shaping up rather well for IoT devices, along with anyone who is making side products that can use the OS. Google says it will be providing new Developer Preview builds with additional features and bug fixes every eight weeks or so, but the company has not yet offered a timeline for when it plans to release the final version.

Are you currently using Android Things on your IoT board, and if so what has your experience been like so far? Please let us know your hands-on impressions in the comments!

Google wants more people to copy and share AMP links

In October 2015, Google first announced its Accelerated Mobile Pages (AMP) program, which is designed to give website publishers a better way to display and load their pages on mobile devices. However, sites who have opted to use AMP have found that users have had issues with copying and sharing links from those pages. Today, Google announced some changes that should make it easier for people to do both with AWP-based sites.

See also:

5 examples of dated app design

June 6, 2016

AMP pages actually have three URLs, according to Google. The first is the original URL for the page, while the second is the AMP Cache URL, which most people won’t ever see. The final one is the AMP Viewer URL, which is the one displayed in Google’s mobile search results.

The first change the company is making is the addition of an anchor button, as shown in the screenshot above, in the AMP Viewer header when a page is displayed in Google Search. This feature will allow the share functionality of a user’s browser by by long-tapping on the link that is displayed. An upcoming update to the Android version of the Google search app will let users share the original URL of a AMP page when the app’s share button is pressed. If you have an iPhone, this feature is already live on the iOS Google search app.

Google added that it is working on updating its Web Share API to let AMP viewers “invoke the platform’s native sharing flow with the original URL rather than the AMP viewer URL”. All of these updates will likely be welcome ones for web publishers that use AMP to make their pages easier to access for smartphones. More importantly, the changes will make it simple for users who access AMP pages on their smartphones to share content with others.

Google hasn’t offered any recent updates on how many publishers are currently using AMP, but hopefully we will get more info as part of the Google I/O developers conference that’s coming up in May.

How to add fingerprint authentication to your Android app

Android 6.0 saw the introduction of fingerprint authentication, a new security feature that allows users to confirm their identify with a single touch. While this new security feature is most commonly used to secure the user’s lockscreen, fingerprint authentication can also be a useful addition to your apps, allowing you to secure sensitive features such as in-app payments, or replace password-and-username screens with a much more convenient single-touch sign in.

In this article, I’m going to show you exactly how to implement fingerprint authentication in your own apps, by walking you through the process of creating a sample app that registers when the user places their fingertip against their device’s touch sensor, processes their input, and then displays a range of toasts depending on whether the fingerprint authentication has succeeded or failed. We’ll also be looking at how to test fingerprint authentication on Android Virtual Devices (AVDs) that don’t feature a physical touch sensor, as well as some best practices to make sure you’re getting the most out of this new feature.

Why should I care about fingerprint authentication?

Adding fingerprint authentication to your project is a multi-step process, so to help you decide whether it’s worth the initial time and effort, let’s look at some of the ways in which fingerprint authentication can improve the user experience:

  • It’s a quick and convenient way of authenticating the user’s identity. While a traditional PIN, pattern or password is an effective security feature, there’s no denying that requiring the user to input a password does add some friction to the user experience. Touching your fingertip to a sensor is far easier than entering a PIN, pattern or password, making fingerprint authentication an effective way of striking a balance between keeping your users safe and providing a frictionless user experience.
  • You can’t forget a fingerprint! Most of us have a long list of passwords we need to remember on a day-to-day basis. Plus, if you follow best practices for creating secure passwords (never use the same password more than once; always use a combination of symbols, numbers, plus upper and lower case characters) then chances are these passwords aren’t particularly easy to remember! Fingerprint authentication can provide your users with all the security of a password, without actually adding to the list of passwords they need to remember on a day-to-day basis.
  • No more struggling with mobile keyboards. Not only are long, complex passwords difficult to remember, they’re also difficult to type on the smaller screen of a mobile device. Even if your app only requests the user’s password once per session, navigating the awkward mobile keyboard can make this feel like one time too many. Also, consider that many mobile users interact with their apps on the go – and no-one wants to be messing around trying to type out a long, complex password when they’re stood up on a busy commuter bus! Fingerprint authentication gives users a way of confirming their identity without them having to go anywhere near the mobile keyboard.
  • No more annoying password recovery or reset. There’s never a good time to forget your password, but forgetting a password for a mobile app can be particularly painful as users tend to interact with mobile apps on the go. If you’re out and about then the last thing you want to do is sit down and navigate an app’s password recovery or reset procedure. By adding fingerprint authentication to your app, you can ensure that your users never have to see your app’s password recovery or reset screens again.
  • Your fingerprint is unique and impossible to guess. Even if your users follow best practices for creating a secure password, there’s no guarantee that someone won’t be able to guess their password anyway, or even manipulate the user’s device into leaking their password via tools such as spyware. While nothing is ever 100% secure, a fingerprint cannot be guessed or stolen in the same way a password can.

Creating our fingerprint authentication project

If you’ve weighed up everything that fingerprint authentication has to offer and have decided that it’s something you want to start using in your apps, then there’s a few steps you’ll need to complete. The most effective way of familiarizing yourself with these steps is to see them in action, so let’s create a sample app that’s capable of performing fingerprint authentication.

Open Android Studio and create a new project. You can use the settings of your choice, but for the sake of simplicity you may want to set your project’s minimum SDK to 23 or higher. This ensures your app is never installed on a device running a version of Android that pre-dates fingerprint authentication.

If you do allow users to install your app on pre-Marshmallow versions of Android, then your app will need to verify what version of Android it’s on, and then disable its fingerprint-related features where appropriate.

Once you’ve created your project, we’ll need to make some adjustments to the Manifest and build the app’s user interface.

Updating the Manifest

Our app is going to require access to the device’s touch sensor in order to receive fingertip touch events. However, the Android operating system runs on a wide range of devices, and not every one of these devices includes a touch sensor.

If fingerprint authentication is essential to your app providing a good user experience, then you should consider preventing your app from being installed on devices that don’t include this piece of hardware. You can declare that your app requires a touch sensor in order to function, by adding the following to your Manifest:

<uses-feature android:name="android.hardware.fingerprint" 
  android:required="true"/>

When you mark a feature as android:required=”true,” the Google Play store will only allow users to install your app on devices that fulfil all of these hardware requirements.

If your app can function without a fingerprint sensor then you should mark the touch sensor as preferred, but not required:

<uses-feature android:name="android.hardware.fingerprint" 
  android:required="false"/>

Google Play will then permit users to download your app even if their device doesn’t have a fingerprint sensor. If you do opt for this approach, then your app will need to check for the presence of a touch sensor at runtime and then disable its fingerprint authentication features, where appropriate.

While it may seem strange to declare a feature in your Manifest just so you can state that your app doesn’t actually need it, declaring every feature your app uses will help to ensure you don’t get caught out by implicit hardware requests.

Certain permissions make implicit hardware requests, for example if you add the android.hardware.camera permission to your Manifest, then this implies that your app requires a camera in order to run. Google Play will then prevent your app from being installed on devices that don’t include camera hardware – unless you explicitly state that your app prefers this hardware to be available, but can function without it. To ensure Google Play doesn’t prevent users from downloading your app based on incorrect assumptions about your app’s requirements, try to get into the habit of declaring every feature that your app uses, and then mark them as android:required=”false” or android:required=”true.”

The final change you’ll need to make to your project’s Manifest, is requesting permission to access the fingerprint sensor:

<uses-permission
  android:name="android.permission.USE_FINGERPRINT" />

Creating your user interface

Next, we’ll need to build our user interface. Open your strings.xml file and add the following:

<resources>
<string name="app_name">Fingerprint Authentication</string>
<string name="instructions">
Place your fingertip on the Home button to verify your identity
</string>
</resources>

Google provides a standard fingerprint icon that they recommend you display whenever your app requests fingerprint authentication from the user, so download this icon and add it to your project’s ‘Drawable’ folder.

Now we have all our resources, let’s create our UI:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/activity_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context="com.jessicathornsby.fingerprintauthentication">

<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="@string/app_name"
  android:textAppearance="@style/TextAppearance.AppCompat.Large"
  android:layout_centerHorizontal="true"/>

<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerInParent="true"
  android:id="@+id/textview"/>

<ImageView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  app:srcCompat="@drawable/fingerprint"
  android:id="@+id/imageView"
  android:layout_below="@+id/textView"
  android:layout_centerHorizontal="true"
  android:layout_marginTop="36dp" />

<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/textView2"
  android:text="@string/instructions"
  android:layout_below="@+id/imageView"
  android:layout_alignParentStart="true"
  android:layout_marginTop="27dp" />
</RelativeLayout>

Your user interface should look something like this:

How to add fingerprint authentication to your Android app

Creating your MainActivity.java file

Now it’s time to implement the fingerprint authentication part of our app.

We’re going to be performing the bulk of the fingerprint authentication in our MainActivity.java file, so I’m going to look at this file in two parts.

In the first half, we’re going to focus on checking that the device has the hardware, software and settings required to support fingerprint authentication, and in the second half we’re going to create the key, cipher and CryptoObject that we’ll use to perform the actual authentication.

Specifically, in this first part of our MainActivity file we’re going to check that:

  • The device is running Android 6.0 or higher. If your project’s minSdkversion is 23 or higher, then you won’t need to perform this check.
  • The device features a fingerprint sensor. If you marked android.hardware.fingerprint as something that your app requires (android:required=”true”) then you don’t need to perform this check.
  • The user has granted your app permission to access the fingerprint sensor.
  • The user has protected their lockscreen. Fingerprints can only be registered once the user has secured their lockscreen with either a PIN, pattern or password, so you’ll need to ensure the lockscreen is secure before proceeding.
  • The user has registered at least one fingerprint on their device.

If any of the above requirements aren’t met, then your app should gracefully disable all features that rely on fingerprint authentication and explain why the user cannot access these features. You may also want to provide the user with an alternative method of confirming their identity, for example by giving them the option to create a password and username.

In addition to completing these tasks, I’m also going to create an instance of FingerprintManager. This is a class that we’ll be using throughout the fingerprint authentication process, which is why it makes sense to establish it early in our MainActivity file.

package com.jessicathornsby.fingerprintauthentication;

import android.app.KeyguardManager;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class MainActivity extends AppCompatActivity {

  // Declare a string variable for the key we’re going to use in our fingerprint authentication
  private static final String KEY_NAME = "yourKey";
  private Cipher cipher;
  private KeyStore keyStore;
  private KeyGenerator keyGenerator;
  private TextView textView;
  private FingerprintManager.CryptoObject cryptoObject;
  private FingerprintManager fingerprintManager;
  private KeyguardManager keyguardManager;

@Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

  // If you’ve set your app’s minSdkVersion to anything lower than 23, then you’ll need to verify that the device is running Marshmallow
  // or higher before executing any fingerprint-related code
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    //Get an instance of KeyguardManager and FingerprintManager//
    keyguardManager =
      (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
    fingerprintManager =
      (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);

    textView = (TextView) findViewById(R.id.textview);

    //Check whether the device has a fingerprint sensor//
    if (!fingerprintManager.isHardwareDetected()) {
      // If a fingerprint sensor isn’t available, then inform the user that they’ll be unable to use your app’s fingerprint functionality//
        textView.setText("Your device doesn't support fingerprint authentication");
    }
    //Check whether the user has granted your app the USE_FINGERPRINT permission//
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
      // If your app doesn't have this permission, then display the following text//
      textView.setText("Please enable the fingerprint permission");
    }

    //Check that the user has registered at least one fingerprint//
    if (!fingerprintManager.hasEnrolledFingerprints()) {
      // If the user hasn’t configured any fingerprints, then display the following message//
      textView.setText("No fingerprint configured. Please register at least one fingerprint in your device's Settings");
    }

    //Check that the lockscreen is secured//
    if (!keyguardManager.isKeyguardSecure()) {
      // If the user hasn’t secured their lockscreen with a PIN password or pattern, then display the following text//
      textView.setText("Please enable lockscreen security in your device's Settings");
    } else {
      try {

If all of these conditions are met, then your app is ready to start the fingerprint authentication process.

In the second half of our MainActivity file, we’re going to complete the following:

  • Gain access to the Android keystore, by generating a Keystore instance. The Android keystore allows you to store cryptographic keys in a way that makes them more difficult to extract from the device. The keystore also restricts how and when each key can be used. To create that fingerprint authentication effect, you just need to specify that the user has to authenticate their identity with a fingerprint every time the want to use this key.
  • Create a new method (I’m going to use generateKey) that’ll be responsible for generating the app’s encryption key.
  • Use the generateKey function to generate the app’s encryption key.
  • Create a new method (I’m using initCipher) that we’ll use to initialize the cipher.
  • Use the Cipher instance to create an encrypted CryptoObject instance.
  • Assign the CryptoObject to the instantiated FingerprintManager.

The second half of our MainActivity file looks like this:

        generateKey();
      } catch (FingerprintException e) {
        e.printStackTrace();
      }

      if (initCipher()) {
        //If the cipher is initialized successfully, then create a CryptoObject instance//
        cryptoObject = new FingerprintManager.CryptoObject(cipher);

       // Here, I’m referencing the FingerprintHandler class that we’ll create in the next section. This class will be responsible
       // for starting the authentication process (via the startAuth method) and processing the authentication process events//
       FingerprintHandler helper = new FingerprintHandler(this);
        helper.startAuth(fingerprintManager, cryptoObject);
      }
    }
 }
}

//Create the generateKey method that we’ll use to gain access to the Android keystore and generate the encryption key//

private void generateKey() throws FingerprintException {
  try {
    // Obtain a reference to the Keystore using the standard Android keystore container identifier (“AndroidKeystore”)//
    keyStore = KeyStore.getInstance("AndroidKeyStore");

    //Generate the key//
    keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");

    //Initialize an empty KeyStore//
    keyStore.load(null);

    //Initialize the KeyGenerator//
    keyGenerator.init(new

    //Specify the operation(s) this key can be used for//
    KeyGenParameterSpec.Builder(KEY_NAME,
    KeyProperties.PURPOSE_ENCRYPT |
        KeyProperties.PURPOSE_DECRYPT)
   .setBlockModes(KeyProperties.BLOCK_MODE_CBC)

    //Configure this key so that the user has to confirm their identity with a fingerprint each time they want to use it//
      .setUserAuthenticationRequired(true)
      .setEncryptionPaddings(
       KeyProperties.ENCRYPTION_PADDING_PKCS7)
    .build());

    //Generate the key//
    keyGenerator.generateKey();

  } catch (KeyStoreException
       | NoSuchAlgorithmException
       | NoSuchProviderException
       | InvalidAlgorithmParameterException
       | CertificateException
       | IOException exc) {
    exc.printStackTrace();
  throw new FingerprintException(exc);
  }
}

//Create a new method that we’ll use to initialize our cipher//
public boolean initCipher() {
  try {
    //Obtain a cipher instance and configure it with the properties required for fingerprint authentication//
    cipher = Cipher.getInstance(
       KeyProperties.KEY_ALGORITHM_AES + "/"
          + KeyProperties.BLOCK_MODE_CBC + "/"
          + KeyProperties.ENCRYPTION_PADDING_PKCS7);
  } catch (NoSuchAlgorithmException |
      NoSuchPaddingException e) {
   throw new RuntimeException("Failed to get Cipher", e);
  }

  try {
    keyStore.load(null);
    SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
          null);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    //Return true if the cipher has been initialized successfully//
    return true;
  } catch (KeyPermanentlyInvalidatedException e) {

  //Return false if cipher initialization failed//
  return false;
  } catch (KeyStoreException | CertificateException
             | UnrecoverableKeyException | IOException
             | NoSuchAlgorithmException | InvalidKeyException e) {
      throw new RuntimeException("Failed to init Cipher", e);
  }
}

private class FingerprintException extends Exception {
  public FingerprintException(Exception e) {
           super(e);
  }
}
}

Creating the fingerprint helper class

Our final task is creating the helper class that we referenced in our MainActivity file. This class will be responsible for triggering the authentication method and processing the various callback events that can occur depending on whether the authentication has succeeded, failed, or an error has occurred.

Create a new FingerprintHandler.java class and add the following:

package com.jessicathornsby.fingerprintauthentication;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.Manifest;
import android.os.CancellationSignal;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.M)
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {

// You should use the CancellationSignal method whenever your app can no longer process user input, for example when your app goes
        // into the background. If you don’t use this method, then other apps will be unable to access the touch sensor, including the lockscreen!//

private CancellationSignal cancellationSignal;
private Context context;

public FingerprintHandler(Context mContext) {
context = mContext;
}

//Implement the startAuth method, which is responsible for starting the fingerprint authentication process//

public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) {

cancellationSignal = new CancellationSignal();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}

@Override
//onAuthenticationError is called when a fatal error has occurred. It provides the error code and error message as its parameters//

public void onAuthenticationError(int errMsgId, CharSequence errString) {

//I’m going to display the results of fingerprint authentication as a series of toasts.
                //Here, I’m creating the message that’ll be displayed if an error occurs//

Toast.makeText(context, "Authentication error\n" + errString, Toast.LENGTH_LONG).show();
}

@Override

//onAuthenticationFailed is called when the fingerprint doesn’t match with any of the fingerprints registered on the device//

public void onAuthenticationFailed() {
Toast.makeText(context, "Authentication failed", Toast.LENGTH_LONG).show();
}

@Override

//onAuthenticationHelp is called when a non-fatal error has occurred. This method provides additional information about the error,
        //so to provide the user with as much feedback as possible I’m incorporating this information into my toast//
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
Toast.makeText(context, "Authentication help\n" + helpString, Toast.LENGTH_LONG).show();
}@Override

//onAuthenticationSucceeded is called when a fingerprint has been successfully matched to one of the fingerprints stored on the user’s device//
public void onAuthenticationSucceeded(
FingerprintManager.AuthenticationResult result) {

Toast.makeText(context, "Success!", Toast.LENGTH_LONG).show();
}

}

How to add fingerprint authentication to your Android app

Testing your project

Whenever you’re working on an Android app, you should test that app across a wide range of Android Virtual Devices (AVDs) plus at least one physical Android smartphone or tablet.

Assuming that you have access to a physical smartphone or tablet that’s running Android 6.0 or higher and features a fingerprint sensor, testing our sample app on a physical Android device should be fairly straightforward.

First, make sure your Android smartphone or tablet is configured to support fingerprint authentication by securing your lockscreen with a PIN, password or pattern and then registering at least one fingerprint on your device. Typically, you register a fingerprint by opening your device’s ‘Settings’ app, selecting ‘Security > Fingerprint,’ and then following the onscreen instructions.

Install and launch the sample app on your device, then put it to the test by placing your fingertip against your device’s fingerprint sensor. The app will then display various toasts depending on whether the authentication succeeds, fails, or an error has occurred. Spend some time making sure the app is reacting to each event correctly.

When it comes to testing Android’s fingerprint authentication on an AVD, there’s an immediate problem: an emulated Android device doesn’t have any physical hardware. However, AVDs are a crucial tool for testing Android apps across a wide range of different hardware and software, so you’ll need to find a way to test fingerprint authentication on an AVD.

The solution, is to use Android Debug Bridge (ADB) commands to fake a touch event. Open your Mac’s Terminal (or Command Prompt if you’re a Windows user) then change directory (cd) so it’s pointing at your Android SDK download; specifically, the Android/sdk/platform-tools folder.

My command looks like this:

cd /Users/jessicathornsby/Library/Android/sdk/platform-tools

Once your Terminal pointing in the right direction, create and launch the AVD you want to use, then install your app on this AVD.

You’ll need to “register” a fingerprint with this device, so navigate to your AVD’s ‘Settings > Security > Fingerprint’ screen. When the AVD prompts you to place your finger against the sensor, fake a fingerprint touch event by typing the following command into your Terminal window:

./adb -s <emulator-ID> emu finger touch <fingerprint ID>

For example, my command looks like this:

./adb -s emulator-5554 emu finger touch 1

Then press the ‘Enter’ key on your keyboard. The AVD should confirm that you’ve successfully registered a new fingerprint:

How to add fingerprint authentication to your Android app

Launch our sample app and re-enter this command into your Terminal, and the AVD will act as though you’ve placed a registered fingerprint against the device’s non-existent fingerprint sensor.

Best Practices

If this sample app has got you eager to try out fingerprint authentication in your own apps, then there’s a few best practices that can help you get the most out of this feature:

  • Consider backwards compatibility. Fingerprint authentication didn’t find its way into the Android platform until version 6.0. While it does have plenty to offer and can greatly improve the user experience, chances are you’re not wild about the idea of creating an app that’s incompatible with every Android device running Lollipop or earlier! We’ve already explored using Build.VERSION checks and @TargetApi annotations to include fingerprint authentication in your app while remaining backwards compatible with earlier versions of Android. However, you can also use the v4 support library, which provides compatibility version of many of the fingerprint classes introduced in Marshmallow. If you do use this library, then when your app is installed on Lollipop or earlier it’ll behave as though the device doesn’t feature a fingerprint sensor – and overlook the fact that the operating system is incapable of supporting fingerprint authentication.
  • Provide alternate methods of authentication. There are a number of reasons why the user might be unable to use your app’s fingerprint authentication. Maybe they’re running a pre-Marshmallow version of Android, maybe their device doesn’t include a fingerprint sensor, or maybe they haven’t configured their device to support fingerprint authentication. However there may also be some users who simply don’t want to use fingerprint authentication – some people may simply prefer to use a traditional password. In order to provide the best possible experience for all your users, you should consider providing an alternate method of authentication for users who are unable or unwilling to use your app’s fingerprint authentication.
  • Clearly indicate when your app is “listening” for user input. Don’t leave the user wondering whether they’re supposed to press their finger to the sensor now, or wait for further instructions. Google recommends that you display the standard fingerprint icon whenever you app is ready to receive a touch event, but depending on the context and your target audience you may want to consider supplementing this icon with clear text instructions – which is exactly what we’re doing with our sample app’s “instructions” string.
  • If the device cannot support finger authentication, then explain why. There’s a list of requirements that a device needs to meet before it can support fingerprint authentication. If the device doesn’t fulfil one or more of these requirements then you should disable all of your app’s fingerprint features, but disabling sections of your app without providing an explanation is never a good idea! Best case scenario, you’ll leave the user wondering what they’ve done wrong – worst case scenario, they’ll assume that your app is broken and leave you a negative review on Google Play. You should always let the user know why they can’t access part of your app and, ideally, provide them with instructions on how they can ‘unlock’ this part of your app’s functionality.
  • Provide the user with plenty of feedback. Whenever the user touches their device’s fingerprint sensor, the authentication can succeed, fail or an error can occur – and you should never leave your users wondering which one has just happened! Imagine you press your fingertip to your device’s touch sensor when prompted, and nothing happens. What went wrong? Maybe some dirt on the sensor interfered with the authentication process; maybe you didn’t press on the sensor long enough, or maybe the app is broken and you should give it a negative review on Google Play immediately? To ensure your users can navigate your app’s fingerprint authentication successfully, use the fingerprint authentication callback methods to provide the user with all the information they need to understand when authentication has failed, and why.

 
How to add fingerprint authentication to your Android app

  • Make it clear that your app supports fingerprint authentication. Fingerprint identification is still a relatively new addition to Android, so it’s possible that users won’t go looking for his feature in your app – and some users may not even be aware that Android offers this kind of functionality in the first place! If it isn’t immediately obvious that your app offers fingerprint authentication, then you may want to consider drawing the user’s attention towards this feature, for example by displaying a dialogue the first time the user launches your app, or featuring fingerprint authentication prominently in your app’s ‘Settings.’

Wrapping Up

In this article we looked at the steps you’ll typically need to complete in order to add fingerprint authentication functionality to your apps – if you want to try this project for yourself, then you’ll find the complete code on GitHub.

There’s a wide range of ways that you can use this kind of single-touch identification to improve the user experience – from adding an extra layer of security to your in-app payments, to providing an easy way to lock and unlock sensitive areas of your app, or even removing the need for users to their and password every time they want to use your app.

If you have any plans to use fingerprint authentication in your projects, then let us know in the comments!

How to add fingerprint authentication to your Android app

Android 6.0 saw the introduction of fingerprint authentication, a new security feature that allows users to confirm their identify with a single touch. While this new security feature is most commonly used to secure the user’s lockscreen, fingerprint authentication can also be a useful addition to your apps, allowing you to secure sensitive features such as in-app payments, or replace password-and-username screens with a much more convenient single-touch sign in.

In this article, I’m going to show you exactly how to implement fingerprint authentication in your own apps, by walking you through the process of creating a sample app that registers when the user places their fingertip against their device’s touch sensor, processes their input, and then displays a range of toasts depending on whether the fingerprint authentication has succeeded or failed. We’ll also be looking at how to test fingerprint authentication on Android Virtual Devices (AVDs) that don’t feature a physical touch sensor, as well as some best practices to make sure you’re getting the most out of this new feature.

Why should I care about fingerprint authentication?

Adding fingerprint authentication to your project is a multi-step process, so to help you decide whether it’s worth the initial time and effort, let’s look at some of the ways in which fingerprint authentication can improve the user experience:

  • It’s a quick and convenient way of authenticating the user’s identity. While a traditional PIN, pattern or password is an effective security feature, there’s no denying that requiring the user to input a password does add some friction to the user experience. Touching your fingertip to a sensor is far easier than entering a PIN, pattern or password, making fingerprint authentication an effective way of striking a balance between keeping your users safe and providing a frictionless user experience.
  • You can’t forget a fingerprint! Most of us have a long list of passwords we need to remember on a day-to-day basis. Plus, if you follow best practices for creating secure passwords (never use the same password more than once; always use a combination of symbols, numbers, plus upper and lower case characters) then chances are these passwords aren’t particularly easy to remember! Fingerprint authentication can provide your users with all the security of a password, without actually adding to the list of passwords they need to remember on a day-to-day basis.
  • No more struggling with mobile keyboards. Not only are long, complex passwords difficult to remember, they’re also difficult to type on the smaller screen of a mobile device. Even if your app only requests the user’s password once per session, navigating the awkward mobile keyboard can make this feel like one time too many. Also, consider that many mobile users interact with their apps on the go – and no-one wants to be messing around trying to type out a long, complex password when they’re stood up on a busy commuter bus! Fingerprint authentication gives users a way of confirming their identity without them having to go anywhere near the mobile keyboard.
  • No more annoying password recovery or reset. There’s never a good time to forget your password, but forgetting a password for a mobile app can be particularly painful as users tend to interact with mobile apps on the go. If you’re out and about then the last thing you want to do is sit down and navigate an app’s password recovery or reset procedure. By adding fingerprint authentication to your app, you can ensure that your users never have to see your app’s password recovery or reset screens again.
  • Your fingerprint is unique and impossible to guess. Even if your users follow best practices for creating a secure password, there’s no guarantee that someone won’t be able to guess their password anyway, or even manipulate the user’s device into leaking their password via tools such as spyware. While nothing is ever 100% secure, a fingerprint cannot be guessed or stolen in the same way a password can.

Creating our fingerprint authentication project

If you’ve weighed up everything that fingerprint authentication has to offer and have decided that it’s something you want to start using in your apps, then there’s a few steps you’ll need to complete. The most effective way of familiarizing yourself with these steps is to see them in action, so let’s create a sample app that’s capable of performing fingerprint authentication.

Open Android Studio and create a new project. You can use the settings of your choice, but for the sake of simplicity you may want to set your project’s minimum SDK to 23 or higher. This ensures your app is never installed on a device running a version of Android that pre-dates fingerprint authentication.

If you do allow users to install your app on pre-Marshmallow versions of Android, then your app will need to verify what version of Android it’s on, and then disable its fingerprint-related features where appropriate.

Once you’ve created your project, we’ll need to make some adjustments to the Manifest and build the app’s user interface.

Updating the Manifest

Our app is going to require access to the device’s touch sensor in order to receive fingertip touch events. However, the Android operating system runs on a wide range of devices, and not every one of these devices includes a touch sensor.

If fingerprint authentication is essential to your app providing a good user experience, then you should consider preventing your app from being installed on devices that don’t include this piece of hardware. You can declare that your app requires a touch sensor in order to function, by adding the following to your Manifest:

<uses-feature android:name="android.hardware.fingerprint" 
  android:required="true"/>

When you mark a feature as android:required=”true,” the Google Play store will only allow users to install your app on devices that fulfil all of these hardware requirements.

If your app can function without a fingerprint sensor then you should mark the touch sensor as preferred, but not required:

<uses-feature android:name="android.hardware.fingerprint" 
  android:required="false"/>

Google Play will then permit users to download your app even if their device doesn’t have a fingerprint sensor. If you do opt for this approach, then your app will need to check for the presence of a touch sensor at runtime and then disable its fingerprint authentication features, where appropriate.

While it may seem strange to declare a feature in your Manifest just so you can state that your app doesn’t actually need it, declaring every feature your app uses will help to ensure you don’t get caught out by implicit hardware requests.

Certain permissions make implicit hardware requests, for example if you add the android.hardware.camera permission to your Manifest, then this implies that your app requires a camera in order to run. Google Play will then prevent your app from being installed on devices that don’t include camera hardware – unless you explicitly state that your app prefers this hardware to be available, but can function without it. To ensure Google Play doesn’t prevent users from downloading your app based on incorrect assumptions about your app’s requirements, try to get into the habit of declaring every feature that your app uses, and then mark them as android:required=”false” or android:required=”true.”

The final change you’ll need to make to your project’s Manifest, is requesting permission to access the fingerprint sensor:

<uses-permission
  android:name="android.permission.USE_FINGERPRINT" />

Creating your user interface

Next, we’ll need to build our user interface. Open your strings.xml file and add the following:

<resources>
<string name="app_name">Fingerprint Authentication</string>
<string name="instructions">
Place your fingertip on the Home button to verify your identity
</string>
</resources>

Google provides a standard fingerprint icon that they recommend you display whenever your app requests fingerprint authentication from the user, so download this icon and add it to your project’s ‘Drawable’ folder.

Now we have all our resources, let’s create our UI:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/activity_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context="com.jessicathornsby.fingerprintauthentication">

<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="@string/app_name"
  android:textAppearance="@style/TextAppearance.AppCompat.Large"
  android:layout_centerHorizontal="true"/>

<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerInParent="true"
  android:id="@+id/textview"/>

<ImageView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  app:srcCompat="@drawable/fingerprint"
  android:id="@+id/imageView"
  android:layout_below="@+id/textView"
  android:layout_centerHorizontal="true"
  android:layout_marginTop="36dp" />

<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/textView2"
  android:text="@string/instructions"
  android:layout_below="@+id/imageView"
  android:layout_alignParentStart="true"
  android:layout_marginTop="27dp" />
</RelativeLayout>

Your user interface should look something like this:

How to add fingerprint authentication to your Android app

Creating your MainActivity.java file

Now it’s time to implement the fingerprint authentication part of our app.

We’re going to be performing the bulk of the fingerprint authentication in our MainActivity.java file, so I’m going to look at this file in two parts.

In the first half, we’re going to focus on checking that the device has the hardware, software and settings required to support fingerprint authentication, and in the second half we’re going to create the key, cipher and CryptoObject that we’ll use to perform the actual authentication.

Specifically, in this first part of our MainActivity file we’re going to check that:

  • The device is running Android 6.0 or higher. If your project’s minSdkversion is 23 or higher, then you won’t need to perform this check.
  • The device features a fingerprint sensor. If you marked android.hardware.fingerprint as something that your app requires (android:required=”true”) then you don’t need to perform this check.
  • The user has granted your app permission to access the fingerprint sensor.
  • The user has protected their lockscreen. Fingerprints can only be registered once the user has secured their lockscreen with either a PIN, pattern or password, so you’ll need to ensure the lockscreen is secure before proceeding.
  • The user has registered at least one fingerprint on their device.

If any of the above requirements aren’t met, then your app should gracefully disable all features that rely on fingerprint authentication and explain why the user cannot access these features. You may also want to provide the user with an alternative method of confirming their identity, for example by giving them the option to create a password and username.

In addition to completing these tasks, I’m also going to create an instance of FingerprintManager. This is a class that we’ll be using throughout the fingerprint authentication process, which is why it makes sense to establish it early in our MainActivity file.

package com.jessicathornsby.fingerprintauthentication;

import android.app.KeyguardManager;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class MainActivity extends AppCompatActivity {

  // Declare a string variable for the key we’re going to use in our fingerprint authentication
  private static final String KEY_NAME = "yourKey";
  private Cipher cipher;
  private KeyStore keyStore;
  private KeyGenerator keyGenerator;
  private TextView textView;
  private FingerprintManager.CryptoObject cryptoObject;
  private FingerprintManager fingerprintManager;
  private KeyguardManager keyguardManager;

@Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

  // If you’ve set your app’s minSdkVersion to anything lower than 23, then you’ll need to verify that the device is running Marshmallow
  // or higher before executing any fingerprint-related code
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    //Get an instance of KeyguardManager and FingerprintManager//
    keyguardManager =
      (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
    fingerprintManager =
      (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);

    textView = (TextView) findViewById(R.id.textview);

    //Check whether the device has a fingerprint sensor//
    if (!fingerprintManager.isHardwareDetected()) {
      // If a fingerprint sensor isn’t available, then inform the user that they’ll be unable to use your app’s fingerprint functionality//
        textView.setText("Your device doesn't support fingerprint authentication");
    }
    //Check whether the user has granted your app the USE_FINGERPRINT permission//
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
      // If your app doesn't have this permission, then display the following text//
      textView.setText("Please enable the fingerprint permission");
    }

    //Check that the user has registered at least one fingerprint//
    if (!fingerprintManager.hasEnrolledFingerprints()) {
      // If the user hasn’t configured any fingerprints, then display the following message//
      textView.setText("No fingerprint configured. Please register at least one fingerprint in your device's Settings");
    }

    //Check that the lockscreen is secured//
    if (!keyguardManager.isKeyguardSecure()) {
      // If the user hasn’t secured their lockscreen with a PIN password or pattern, then display the following text//
      textView.setText("Please enable lockscreen security in your device's Settings");
    } else {
      try {

If all of these conditions are met, then your app is ready to start the fingerprint authentication process.

In the second half of our MainActivity file, we’re going to complete the following:

  • Gain access to the Android keystore, by generating a Keystore instance. The Android keystore allows you to store cryptographic keys in a way that makes them more difficult to extract from the device. The keystore also restricts how and when each key can be used. To create that fingerprint authentication effect, you just need to specify that the user has to authenticate their identity with a fingerprint every time the want to use this key.
  • Create a new method (I’m going to use generateKey) that’ll be responsible for generating the app’s encryption key.
  • Use the generateKey function to generate the app’s encryption key.
  • Create a new method (I’m using initCipher) that we’ll use to initialize the cipher.
  • Use the Cipher instance to create an encrypted CryptoObject instance.
  • Assign the CryptoObject to the instantiated FingerprintManager.

The second half of our MainActivity file looks like this:

        generateKey();
      } catch (FingerprintException e) {
        e.printStackTrace();
      }

      if (initCipher()) {
        //If the cipher is initialized successfully, then create a CryptoObject instance//
        cryptoObject = new FingerprintManager.CryptoObject(cipher);

       // Here, I’m referencing the FingerprintHandler class that we’ll create in the next section. This class will be responsible
       // for starting the authentication process (via the startAuth method) and processing the authentication process events//
       FingerprintHandler helper = new FingerprintHandler(this);
        helper.startAuth(fingerprintManager, cryptoObject);
      }
    }
 }
}

//Create the generateKey method that we’ll use to gain access to the Android keystore and generate the encryption key//

private void generateKey() throws FingerprintException {
  try {
    // Obtain a reference to the Keystore using the standard Android keystore container identifier (“AndroidKeystore”)//
    keyStore = KeyStore.getInstance("AndroidKeyStore");

    //Generate the key//
    keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");

    //Initialize an empty KeyStore//
    keyStore.load(null);

    //Initialize the KeyGenerator//
    keyGenerator.init(new

    //Specify the operation(s) this key can be used for//
    KeyGenParameterSpec.Builder(KEY_NAME,
    KeyProperties.PURPOSE_ENCRYPT |
        KeyProperties.PURPOSE_DECRYPT)
   .setBlockModes(KeyProperties.BLOCK_MODE_CBC)

    //Configure this key so that the user has to confirm their identity with a fingerprint each time they want to use it//
      .setUserAuthenticationRequired(true)
      .setEncryptionPaddings(
       KeyProperties.ENCRYPTION_PADDING_PKCS7)
    .build());

    //Generate the key//
    keyGenerator.generateKey();

  } catch (KeyStoreException
       | NoSuchAlgorithmException
       | NoSuchProviderException
       | InvalidAlgorithmParameterException
       | CertificateException
       | IOException exc) {
    exc.printStackTrace();
  throw new FingerprintException(exc);
  }
}

//Create a new method that we’ll use to initialize our cipher//
public boolean initCipher() {
  try {
    //Obtain a cipher instance and configure it with the properties required for fingerprint authentication//
    cipher = Cipher.getInstance(
       KeyProperties.KEY_ALGORITHM_AES + "/"
          + KeyProperties.BLOCK_MODE_CBC + "/"
          + KeyProperties.ENCRYPTION_PADDING_PKCS7);
  } catch (NoSuchAlgorithmException |
      NoSuchPaddingException e) {
   throw new RuntimeException("Failed to get Cipher", e);
  }

  try {
    keyStore.load(null);
    SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
          null);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    //Return true if the cipher has been initialized successfully//
    return true;
  } catch (KeyPermanentlyInvalidatedException e) {

  //Return false if cipher initialization failed//
  return false;
  } catch (KeyStoreException | CertificateException
             | UnrecoverableKeyException | IOException
             | NoSuchAlgorithmException | InvalidKeyException e) {
      throw new RuntimeException("Failed to init Cipher", e);
  }
}

private class FingerprintException extends Exception {
  public FingerprintException(Exception e) {
           super(e);
  }
}
}

Creating the fingerprint helper class

Our final task is creating the helper class that we referenced in our MainActivity file. This class will be responsible for triggering the authentication method and processing the various callback events that can occur depending on whether the authentication has succeeded, failed, or an error has occurred.

Create a new FingerprintHandler.java class and add the following:

package com.jessicathornsby.fingerprintauthentication;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.Manifest;
import android.os.CancellationSignal;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.M)
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {

// You should use the CancellationSignal method whenever your app can no longer process user input, for example when your app goes
        // into the background. If you don’t use this method, then other apps will be unable to access the touch sensor, including the lockscreen!//

private CancellationSignal cancellationSignal;
private Context context;

public FingerprintHandler(Context mContext) {
context = mContext;
}

//Implement the startAuth method, which is responsible for starting the fingerprint authentication process//

public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) {

cancellationSignal = new CancellationSignal();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}

@Override
//onAuthenticationError is called when a fatal error has occurred. It provides the error code and error message as its parameters//

public void onAuthenticationError(int errMsgId, CharSequence errString) {

//I’m going to display the results of fingerprint authentication as a series of toasts.
                //Here, I’m creating the message that’ll be displayed if an error occurs//

Toast.makeText(context, "Authentication error\n" + errString, Toast.LENGTH_LONG).show();
}

@Override

//onAuthenticationFailed is called when the fingerprint doesn’t match with any of the fingerprints registered on the device//

public void onAuthenticationFailed() {
Toast.makeText(context, "Authentication failed", Toast.LENGTH_LONG).show();
}

@Override

//onAuthenticationHelp is called when a non-fatal error has occurred. This method provides additional information about the error,
        //so to provide the user with as much feedback as possible I’m incorporating this information into my toast//
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
Toast.makeText(context, "Authentication help\n" + helpString, Toast.LENGTH_LONG).show();
}@Override

//onAuthenticationSucceeded is called when a fingerprint has been successfully matched to one of the fingerprints stored on the user’s device//
public void onAuthenticationSucceeded(
FingerprintManager.AuthenticationResult result) {

Toast.makeText(context, "Success!", Toast.LENGTH_LONG).show();
}

}

How to add fingerprint authentication to your Android app

Testing your project

Whenever you’re working on an Android app, you should test that app across a wide range of Android Virtual Devices (AVDs) plus at least one physical Android smartphone or tablet.

Assuming that you have access to a physical smartphone or tablet that’s running Android 6.0 or higher and features a fingerprint sensor, testing our sample app on a physical Android device should be fairly straightforward.

First, make sure your Android smartphone or tablet is configured to support fingerprint authentication by securing your lockscreen with a PIN, password or pattern and then registering at least one fingerprint on your device. Typically, you register a fingerprint by opening your device’s ‘Settings’ app, selecting ‘Security > Fingerprint,’ and then following the onscreen instructions.

Install and launch the sample app on your device, then put it to the test by placing your fingertip against your device’s fingerprint sensor. The app will then display various toasts depending on whether the authentication succeeds, fails, or an error has occurred. Spend some time making sure the app is reacting to each event correctly.

When it comes to testing Android’s fingerprint authentication on an AVD, there’s an immediate problem: an emulated Android device doesn’t have any physical hardware. However, AVDs are a crucial tool for testing Android apps across a wide range of different hardware and software, so you’ll need to find a way to test fingerprint authentication on an AVD.

The solution, is to use Android Debug Bridge (ADB) commands to fake a touch event. Open your Mac’s Terminal (or Command Prompt if you’re a Windows user) then change directory (cd) so it’s pointing at your Android SDK download; specifically, the Android/sdk/platform-tools folder.

My command looks like this:

cd /Users/jessicathornsby/Library/Android/sdk/platform-tools

Once your Terminal pointing in the right direction, create and launch the AVD you want to use, then install your app on this AVD.

You’ll need to “register” a fingerprint with this device, so navigate to your AVD’s ‘Settings > Security > Fingerprint’ screen. When the AVD prompts you to place your finger against the sensor, fake a fingerprint touch event by typing the following command into your Terminal window:

./adb -s <emulator-ID> emu finger touch <fingerprint ID>

For example, my command looks like this:

./adb -s emulator-5554 emu finger touch 1

Then press the ‘Enter’ key on your keyboard. The AVD should confirm that you’ve successfully registered a new fingerprint:

How to add fingerprint authentication to your Android app

Launch our sample app and re-enter this command into your Terminal, and the AVD will act as though you’ve placed a registered fingerprint against the device’s non-existent fingerprint sensor.

Best Practices

If this sample app has got you eager to try out fingerprint authentication in your own apps, then there’s a few best practices that can help you get the most out of this feature:

  • Consider backwards compatibility. Fingerprint authentication didn’t find its way into the Android platform until version 6.0. While it does have plenty to offer and can greatly improve the user experience, chances are you’re not wild about the idea of creating an app that’s incompatible with every Android device running Lollipop or earlier! We’ve already explored using Build.VERSION checks and @TargetApi annotations to include fingerprint authentication in your app while remaining backwards compatible with earlier versions of Android. However, you can also use the v4 support library, which provides compatibility version of many of the fingerprint classes introduced in Marshmallow. If you do use this library, then when your app is installed on Lollipop or earlier it’ll behave as though the device doesn’t feature a fingerprint sensor – and overlook the fact that the operating system is incapable of supporting fingerprint authentication.
  • Provide alternate methods of authentication. There are a number of reasons why the user might be unable to use your app’s fingerprint authentication. Maybe they’re running a pre-Marshmallow version of Android, maybe their device doesn’t include a fingerprint sensor, or maybe they haven’t configured their device to support fingerprint authentication. However there may also be some users who simply don’t want to use fingerprint authentication – some people may simply prefer to use a traditional password. In order to provide the best possible experience for all your users, you should consider providing an alternate method of authentication for users who are unable or unwilling to use your app’s fingerprint authentication.
  • Clearly indicate when your app is “listening” for user input. Don’t leave the user wondering whether they’re supposed to press their finger to the sensor now, or wait for further instructions. Google recommends that you display the standard fingerprint icon whenever you app is ready to receive a touch event, but depending on the context and your target audience you may want to consider supplementing this icon with clear text instructions – which is exactly what we’re doing with our sample app’s “instructions” string.
  • If the device cannot support finger authentication, then explain why. There’s a list of requirements that a device needs to meet before it can support fingerprint authentication. If the device doesn’t fulfil one or more of these requirements then you should disable all of your app’s fingerprint features, but disabling sections of your app without providing an explanation is never a good idea! Best case scenario, you’ll leave the user wondering what they’ve done wrong – worst case scenario, they’ll assume that your app is broken and leave you a negative review on Google Play. You should always let the user know why they can’t access part of your app and, ideally, provide them with instructions on how they can ‘unlock’ this part of your app’s functionality.
  • Provide the user with plenty of feedback. Whenever the user touches their device’s fingerprint sensor, the authentication can succeed, fail or an error can occur – and you should never leave your users wondering which one has just happened! Imagine you press your fingertip to your device’s touch sensor when prompted, and nothing happens. What went wrong? Maybe some dirt on the sensor interfered with the authentication process; maybe you didn’t press on the sensor long enough, or maybe the app is broken and you should give it a negative review on Google Play immediately? To ensure your users can navigate your app’s fingerprint authentication successfully, use the fingerprint authentication callback methods to provide the user with all the information they need to understand when authentication has failed, and why.

 
How to add fingerprint authentication to your Android app

  • Make it clear that your app supports fingerprint authentication. Fingerprint identification is still a relatively new addition to Android, so it’s possible that users won’t go looking for his feature in your app – and some users may not even be aware that Android offers this kind of functionality in the first place! If it isn’t immediately obvious that your app offers fingerprint authentication, then you may want to consider drawing the user’s attention towards this feature, for example by displaying a dialogue the first time the user launches your app, or featuring fingerprint authentication prominently in your app’s ‘Settings.’

Wrapping Up

In this article we looked at the steps you’ll typically need to complete in order to add fingerprint authentication functionality to your apps – if you want to try this project for yourself, then you’ll find the complete code on GitHub.

There’s a wide range of ways that you can use this kind of single-touch identification to improve the user experience – from adding an extra layer of security to your in-app payments, to providing an easy way to lock and unlock sensitive areas of your app, or even removing the need for users to their and password every time they want to use your app.

If you have any plans to use fingerprint authentication in your projects, then let us know in the comments!