Print Friendly, PDF & Email

Hello Readers, today I have come up with a new exciting topic, that is how to add captcha feature to your Android app. Let’s go ahead to discuss more things about what is captcha, how it will be useful and how to integrate this feature into your app.


Captcha is an acronym which stands for (Completely Automated Public Turing test to Tell Computers and Humans Apart). It is a service which is used to know whether my app users were humans or bots so, it helps to defend your app from the bots.

How it works

Captcha technology is based on Turing test, the test can be passed only by humans but difficult for bots to pass. It simply asks the end user to perform some task for that the user is shown a word or image which is recognized by the application. The input given by the user is compared with the correct answer. If the answer matches the user is identified as human.

Type of Captchas

We have different types of captchas to use based on our app requirements we can choose.

1. The standard Captcha with an audio option:

Here the user is shown with a scrambled word which the user has to enter the same word in the box below. The user gets an option for next word if the current word is difficult to recognize. A visually disabled person can use the audio option to hear the word.

2. Recognize Image

In this type of captcha, the client is solicited to choose the particular kind from pictures as appeared in the above figure. In this example, the user is asked to select all the images of cars.

3. 3-D Captcha

Here in the above image as shown the 3-D form which is more difficult for the user to solve but it keeps the bots out.

4. Ad-injected Captcha

It can also be called Commercial Captchas, If the user is spending 10 seconds over a captcha then why not to display an add beside it? yes, the same happens here, while the user solves the captcha the user is shown with an AD. The demo is shown in above figure.

Applications for Captcha

Captchas have several applications for practical security.

1. Protecting app registration.

2. Protecting Email Addresses from Scrappers

3. Preventing comment spam in Blogs

4. Online polls.

Building the Project

1. Open your Android Studio

2. Go to File menu->New->New Project

3. Application name: Captcha

4. Company domain: Your package name

5. Click on Next button.

6. Minimum SDK: Android 4.4 (KitKat).

7. Again click on Next button.

8. Select Empty Activity and click Next button.

9. Activity Name: MainActivity.

10. Click Finish button.

This will create your Android application Project named as Captcha.

Integrating SafetyNet reCaptcha API

1. Open app level build.gradle file and the below dependencies.

dependencies {
        compile ''
        compile ''
        compile ''
        compile ''

2. Click on the Sync now in Android Studio.

3. Open your AndroidManifest.xml and copy the below code in that file.

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

4. To use the internet in our application we need to give required permissions in AndroidManifest file.

5. AndroidManifest.xml file looks like this.


<?xml version="1.0" encoding = "utf-8"?>
<manifest xmlns:android = ""
 package = "com.loginworks.captcha">
 <uses-permission android:name = "android.permission.INTERNET"></uses-permission>
 android:allowBackup = "true"
 android:icon ="@mipmap/ic_launcher"
 android:label ="@string/app_name"
 android:roundIcon ="@mipmap/ic_launcher_round"
 android:supportsRtl ="true"
 android:theme ="@style/AppTheme" >
 <activity android:name =".MainActivity" >
 <action android:name ="android.intent.action.MAIN" />
 <category android:name ="android.intent.category.LAUNCHER" />

6. Copy the package name from the AndroidManifest.xml

7. Go to the link

8. Paste the above-copied package name in the below Label.

9. Choose the reCaptcha Android.

10. Paste the same package name at Package Names

11. Accept the reCaptcha Terms of Service.

12. Click on Register button.

13. After Registration done you will get the Site Key and Secret key, please save it for future purpose.

Creating UI

To create the UI open activity_main.xml which is below the layout folder, and copy the below code as shown.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    tools:context="com.loginworks.captcha.MainActivity" >

Creating Actions

Now to create the actions/functionality in MainActivity file just follow this.

Open the MainActivity file and copy the below code.

package com.loginworks.captcha;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity
final String SiteKey = "6LcW0UwUAAAAAFQfFY1a-7AxSZxNSu0usk2JwhLC";
final String SecretKey = "6LcW0UwUAAAAAL4zYZyigh97pa73rz6jxmrSJR-a";
public String TAG = "Main Activity";
public String userResponseToken;
Button btnRequest;
protected void onCreate(Bundle savedInstanceState) {
btnRequest = (Button) findViewById(;
public void connect(View v) {
new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
// Indicates communication with reCAPTCHA service was
// successful.
userResponseToken = response.getTokenResult();
Log.d(TAG,"response "+userResponseToken);
if (!userResponseToken.isEmpty()) {
new Check().execute();
.addOnFailureListener(this, new OnFailureListener() {
public void onFailure(@NonNull Exception e) {
if (e instanceof ApiException) {
// An error occurred when communicating with the
// reCAPTCHA service. Refer to the status code to
// handle the error appropriately.
ApiException apiException = (ApiException) e;
int statusCode = apiException.getStatusCode();
Log.d(TAG, "Error: " + CommonStatusCodes
} else {
// A different, unknown type of error occurred.
Log.d(TAG, "Error: " + e.getMessage());
public class Check extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please Wait ");;
protected String doInBackground(String... strings) {
String isSuccess="";
InputStream is = null;
String API="";
String newAPI=API+"secret="+SecretKey+"&response="+userResponseToken;
Log.d(TAG," API  " +newAPI);
try {
URL url = new URL(newAPI);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(8000 /* milliseconds */);
httpURLConnection.setConnectTimeout(4000 /* milliseconds */);
// Starts the query
int response = httpURLConnection.getResponseCode();
is = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
String result = stringBuilder.toString();
Log.d("Api", result);
try {
JSONObject jsonObject = new JSONObject(result);
System.out.println("Result Object :  " + jsonObject);
isSuccess = jsonObject.getString("success");
System.out.println("obj "+isSuccess);
} catch (Exception e) {
Log.d("Exception: ", e.getMessage());
} catch (Exception e) {
return isSuccess;
protected void onPostExecute(String s) {
try {
if (s != null) {
switch (s) {
case "true":
return ;
case "socketexception":
} catch (Exception ex) {

Launching the App

Now it’s time to launch our app by clicking the run button or we can use shift+10 in your android studio.

Outcome Screens

1. After clicking the run the app will be open on the device and you first observe the screen which is this way, having with one button CAPTCHA as shown above figure.

2. Tap on the button CAPTCHA, it will prompt the above screen as demonstrated that is checking you’re, not a robot.

3.Next, it will create another screen with demonstrating the pictures and requesting that the client select the predefined ones.

4. Select the specified images and click on the VERIFY button.


Thanks for reading this far, hope this blog will give you useful info to implement the captcha feature in your Android app. Keep reading and comment your queries in the comment section below.


Please enter your comment!
Please enter your name here