Figure 0 Introduction: In this article, we will learn what is reCaptcha for Android and how to integrate the same to Android Apps....

How to integrate Google’s reCaptcha Validation in Android How to integrate Google’s reCaptcha Validation in Android

A blog about android developement

Figure 0

Introduction:

In this article, we will learn what is reCaptcha for Android and how to integrate the same to Android Apps. This options is provided by Google. Google’s reCaptcha API protects your app from malicious traffic and it is integrated with your Android apps using SafetyNet API. The service is free to use and it will show a Captcha to be solved if the engine suspects user interaction to be a bot instead of human.

How it works:

The following points explains the simple flow of reCaptcha in Android with SafetyNet API.
  1. We need to get site key pair from SafetyNet by registering your app.
  2. We will get Site Key and Secret.
  3. Get user response token from safety net server using SafetyNet API in Android.
  4. Then validate the token with the SafetyNet server using the curl commands and site key.

Registering your App with SafetyNet Server:

  1. Open reCaptcha site from the following link.
  2. Then go to register new site Section and Select Option reCAPTCHA Android. The following figure explains the same.
    Figure 1
  3. Then add your Package Name in Package Names Section as shown in the above figure. We can add multiple apps and each can be separated by enter or new line.
  4. Then Check or select the Accept Terms Checkbox and click Register button. The following figure shows the same.
    Figure 2
  5. Then you will get the site key and secret key from SafetyNet API Server and as well as shows client and server side integration code snippets. The following figures shows the same
    Figure 3
    Figure 4

Coding Part:

Steps:
I have divided this Implementation into 4 steps as shown in the following.
Step 1: Creating New Project with Android Studio.
Step 2: Setting up the library and AndroidManifest for the project.
Step 3: Implementation of the SafetyNet API.
Step 4: Captcha Response Token Validation.

Step 1: Creating New Project with Android Studio

  1. Open Android Studio and Select create a new project.
  2. Name the project as per your wish and select an Empty activity.

    Android
    Figure 2
  3. Click finish button to create a new project in Android Studio.

Step 2: Setting up the library and AndroidManifest for the project

  1. Add google play service library dependency in your app level build.gradle file. Here, I used the following dependency. You can change as per your Android SDK.
    implementation 'com.google.android.gms:play-services-safetynet:15.0.1'
    implementation 'com.android.volley:volley:1.1.0’
  2. Then click “Sync Now” to add the library.
  3. Now open your Manifest File (AndroidManifest.xml) and the following permission.
    <uses-permission android:name="android.permission.INTERNET" />
  4. SafetyNet library is used to Create Captcha Validation in Android.
    Volley Library is a HTTP Networking Library used here for validating Captcha Response.

Step 3: Implementation of SafetyNet API:

  1. Add the following to get the Captcha Token from SafetyNet Server.
    SafetyNet.getClient(this).verifyWithRecaptcha(SITE_KEY)
                    .addOnSuccessListener(this, new OnSuccessListener() {
                        @Override
                        public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
                            if (!response.getTokenResult().isEmpty()) {
                                handleCaptchaResult(response.getTokenResult());
                            }
                        }
                    })
                    .addOnFailureListener(this, new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            if (e instanceof ApiException) {
                                ApiException apiException = (ApiException) e;
                                Log.d(TAG, "Error message: " +
                                        CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()));
                            } else {
                                Log.d(TAG, "Unknown type of error: " + e.getMessage());
                            }
                        }
                    });
  2. Replace “SITE_KEY” with your appropriate “Site Key” get from SafetyNet API while registering app.
  3. The API will check the Server and it has a separate callbacks from success and failure.
  4. At Success, we will get Captcha Response Token which will be used to validate the user interaction is made by bot or real human.
  5. We will discuss how to validate the token with SafetyNet API Server in next step.

Step 4: Captcha Response Token Validation

  1. We have to verify the token getting from the server using the secret key.
  2. It can achieve by using the following. API Link - https://www.google.com/recaptcha/api/siteverify Method - POST Params – secret, response (We have to pass the “SECRET_KEY” and “TOKEN” respectively)
  3. Volley Library is used to verify the same.
    String url = "https://www.google.com/recaptcha/api/siteverify";
     StringRequest request = new StringRequest(Request.Method.POST, url,
       new Response.Listener() {
        @Override
        public void onResponse(String response) {
         try {
          JSONObject jsonObject = new JSONObject(response);
          if(jsonObject.getBoolean("success")){
           tvVerify.setText("You're not a Robot");
          }
         } catch (Exception ex) {
          Log.d(TAG, "Error message: " + ex.getMessage());
    
         }
        }
       },
       new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
         Log.d(TAG, "Error message: " + error.getMessage());
        }
       }) {
      @Override
      protected Map getParams() {
       Map params = new HashMap<>();
       params.put("secret", SITE_SECRET_KEY);
       params.put("response", responseToken);
       return params;
      }
     };
     request.setRetryPolicy(new DefaultRetryPolicy(
       50000,
       DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
       DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
     queue.add(request);
  4. Volley has - RequestQueue to maintain the server calls in queue. - RetryPolicy to retry the server call if it is fail with TimeOut and Retry Count. We can change those values. - StringRequest is used for getting Response as JSON String. - Request.Method.POST denotes the call as POST method. - Params are passed to server using Map, HashMap.
  5. The SafetyNet API provides the response respective to the parameters passed and the success is Boolean Datatype. We can learn further about volley library in future.

Full Code:

You can find the full code implementation of the API.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button btnVerify;
    TextView tvVerify;
    String TAG = MainActivity.class.getSimpleName();
    String SITE_KEY = " SITE_KEY";
    String SITE_SECRET_KEY = " SITE_SECRET_KEY";
    RequestQueue queue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnVerify = findViewById(R.id.btn_verify);
        tvVerify = findViewById(R.id.tv_verify);
        btnVerify.setOnClickListener(this);

        queue = Volley.newRequestQueue(getApplicationContext());
    }

    @Override
    public void onClick(View view) {
        SafetyNet.getClient(this).verifyWithRecaptcha(SITE_KEY)
                .addOnSuccessListener(this, new OnSuccessListener() {
                    @Override
                    public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
                        if (!response.getTokenResult().isEmpty()) {
                            handleCaptchaResult(response.getTokenResult());
                        }
                    }
                })
                .addOnFailureListener(this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        if (e instanceof ApiException) {
                            ApiException apiException = (ApiException) e;
                            Log.d(TAG, "Error message: " +
                                    CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()));
                        } else {
                            Log.d(TAG, "Unknown type of error: " + e.getMessage());
                        }
                    }
                });
    }

    void handleCaptchaResult(final String responseToken) {
        String url = "https://www.google.com/recaptcha/api/siteverify";
        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if(jsonObject.getBoolean("success")){
                                tvVerify.setText("You're not a Robot");
                            }
                        } catch (Exception ex) {
                            Log.d(TAG, "Error message: " + ex.getMessage());

                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, "Error message: " + error.getMessage());
                    }
                }) {
            @Override
            protected Map getParams() {
                Map params = new HashMap<>();
                params.put("secret", SITE_SECRET_KEY);
                params.put("response", responseToken);
                return params;
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(
                50000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(request);
    }
}

Demo:

You can find the demo in YouTube.

 
Download Code
If you think this article is informative do like and star the repo in GitHub. You can download the full sample code here.

In this tutorial, we will learn how to do Optical Character Recognition by Camera in Android using Vision API. Here, we will just impor...

Optical Character Recognition By Camera Using Google Vision API On Android Optical Character Recognition By Camera Using Google Vision API On Android

A blog about android developement

ocr
In this tutorial, we will learn how to do Optical Character Recognition by Camera in Android using Vision API. Here, we will just import the Google Vision API Library with Android Studio and implement the OCR for retrieving text from camera preview.
You can find my previous tutorial on Optical Character Recognition using Google Vision API for Recognizing Text from Image in here. My previous tutorial covered the introduction about Google Vision API. Therefore, without any delay, we will skip into our coding part.

Coding Part:

Steps: 
I have split this part into four steps as in the following. 
Step 1: Creating New Project with Empty Activity and Gradle Setup. 
Step 2: Setting up Manifest for OCR. 
Step 3: Implementing Camera View using SurfaceView. 
Step 4: Implementing OCR in Application.

Step 1: Creating New Project with Empty Activity and Gradle Setup

We will start coding for OCR. Create New Android Project. Add the following line in your app level build.gradle file to import the library.
implementation 'com.google.android.gms:play-services-vision:15.2.0'
Step 2: Setting up Manifest for OCR
Open your Manifest file and add the following code block to instruct the app to install or download the dependencies at the time of installing the app.
<meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" android:value="ocr"/>

Step 3: Implementing Camera View using SurfaceView

Open your activity_main.xml file and paste the following code. It just the designer part of the application.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidmads.ocrcamera.MainActivity">

    <SurfaceView
        android:id="@+id/surface_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView
        android:id="@+id/txtview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        android:text="No Text"
        android:textColor="@android:color/white"
        android:textSize="20sp"
        android:padding="5dp"/>

</android.support.constraint.ConstraintLayout>

Step 4: Implementing OCR in Application

Open your MainActivity.java file and initialize the widget used in your designer. Add the following code to start Camera View. 
  • Implement your Activity with SurfaceHolder.Callback, Detector.Processor to start your camera preview.
TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!txtRecognizer.isOperational()) {
    Log.e("Main Activity", "Detector dependencies are not yet available");
} else {
    cameraSource = new CameraSource.Builder(getApplicationContext(), txtRecognizer)
            .setFacing(CameraSource.CAMERA_FACING_BACK)
            .setRequestedPreviewSize(1280, 1024)
            .setRequestedFps(2.0f)
            .setAutoFocusEnabled(true)
            .build();
    cameraView.getHolder().addCallback(this);
    txtRecognizer.setProcessor(this);
}
Here, TextRecognizer is used to do Character Recognition in Camera Preview & txtRecognizer.isOperational() is used to check the device has the support for Google Vision API. The output of the TextRecognizer can be retrieved by using SparseArray and StringBuilder. 
TextBlock:
I have used TextBlock to retrieve the paragraph from the image using OCR.
Lines:
You can get the line from the TextBlock using
textblockName.getComponents()
Element:
You can get the line from the Lines using
lineName.getComponents()
Camera Source is starts on surface created with callback and do the scanning process. The Received Detections are read by SparseArray and is similar to read data with bitmap in android. The Text View in the bottom of screen used to preview the scanned data lively.

Full Code:

You can find the full code here.
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, Detector.Processor {

    private SurfaceView cameraView;
    private TextView txtView;
    private CameraSource cameraSource;

    @SuppressLint("MissingPermission")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    try {
                        cameraSource.start(cameraView.getHolder());
                    } catch (Exception e) {

                    }
                }
            }
            break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cameraView = findViewById(R.id.surface_view);
        txtView = findViewById(R.id.txtview);
        TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
        if (!txtRecognizer.isOperational()) {
            Log.e("Main Activity", "Detector dependencies are not yet available");
        } else {
            cameraSource = new CameraSource.Builder(getApplicationContext(), txtRecognizer)
                    .setFacing(CameraSource.CAMERA_FACING_BACK)
                    .setRequestedPreviewSize(1280, 1024)
                    .setRequestedFps(2.0f)
                    .setAutoFocusEnabled(true)
                    .build();
            cameraView.getHolder().addCallback(this);
            txtRecognizer.setProcessor(this);
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},1);
                return;
            }
            cameraSource.start(cameraView.getHolder());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        cameraSource.stop();
    }

    @Override
    public void release() {

    }

    @Override
    public void receiveDetections(Detector.Detections detections) {
        SparseArray items = detections.getDetectedItems();
        final StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < items.size(); i++)
        {
            TextBlock item = (TextBlock)items.valueAt(i);
            strBuilder.append(item.getValue());
            strBuilder.append("/");
            // The following Process is used to show how to use lines & elements as well
            for (int j = 0; j < items.size(); j++) {
                TextBlock textBlock = (TextBlock) items.valueAt(j);
                strBuilder.append(textBlock.getValue());
                strBuilder.append("/");
                for (Text line : textBlock.getComponents()) {
                    //extract scanned text lines here
                    Log.v("lines", line.getValue());
                    strBuilder.append(line.getValue());
                    strBuilder.append("/");
                    for (Text element : line.getComponents()) {
                        //extract scanned text words here
                        Log.v("element", element.getValue());
                        strBuilder.append(element.getValue());
                    }
                }
            }
        }
        Log.v("strBuilder.toString()", strBuilder.toString());

        txtView.post(new Runnable() {
            @Override
            public void run() {
                txtView.setText(strBuilder.toString());
            }
        });
    }
}

Download Code:

You can download the full source code for this article from GitHub. If you like this article, do like the repo and share the article.

Introduction In this article, we will learn how to use  Firebase Cloud Fire Store  in Android and how to do CRUD operations with Fir...

CRUD Operations With Firebase Cloud Fire Store CRUD Operations With Firebase Cloud Fire Store

A blog about android developement


Introduction
In this article, we will learn how to use Firebase Cloud Fire Store in Android and how to do CRUD operations with Firebase Cloud Fire Store.
Getting started with Firebase
Read the following to learn how to set up the Firebase in your Android project.
Reference - https://androidmads.blogspot.in/2016/10/android-getting-started-with-firebase.html
Additionally, do the following for Cloud Firestore.
You can enable the test mode to make the database accessible to all users.
Android
At this point, the empty DB is created as shown in the figure below.
Android
Firebase Cloud Fire store
It is a flexible, scalable NoSQL cloud database to store and sync data for client- and server-side development.
Key capabilities
  • Flexibility
  • Expressive Querying
  • Real-time Updates
  • Offline Support
  • Designed to Scale
Concepts
Firestore hosted the data like NoSQL Database.
Database             ->            Collections
Table                     ->            Document
Column                ->            Field
Coding Part
I have split this part into 3 steps as in the following.
Step 1 - Creating New Project with Empty Activity.
Step 2 - Setting up the Firebase Library.
Step 3 - Implementation of CRUD with Cloud Firestore.
Step 1 - Create a new project with Empty Activity
  1. Open Android Studio and Select create a new project.
  2. Name the project as per your wish and select an Empty activity.

    Android
  3. Click finish button to create a new project in Android Studio.
Step 2 - Setting up the Firebase Library
In this part, we will see how to setup the library for the project.
1. Open your project level build.gradle file and add the following lines in dependencies
dependencies {  
    …  
    classpath 'com.google.gms:google-services:3.1.0'  
              …  
}
2. Then add the following lines in all projects in the project level build.gradle file.
allprojects {  
    repositories {  
        google()  
        jcenter()  
        maven {  
            url "https://maven.google.com"  
        }  
    }  
}
3. Then add the following lines in app level build.gradle file to apply Google services to your project.
dependencies {  
    ...  
    implementation 'com.google.firebase:firebase-firestore:11.8.0'  
}
4. Then click “Sync Now” to set up your project.
Step 3 - Implementation of CRUD with Cloud Firestore
In this part, we will see how to implement CRUD operations with Firestore.
First, we will initialize the Firestore Database.
FirebaseFirestore myDB;  
// Init FireStore  
myDB = FirebaseFirestore.getInstance();
INSERT DATA
You can insert the data to Firestore like the following.
Map data = new HashMap<>();  
data.put("task_name", edtData.getText().toString());  
myDB.collection("tasks")  
 .add(data)  
 .addOnSuccessListener(new OnSuccessListener() {  
  @Override  
  public void onSuccess(DocumentReference documentReference) {  
   toastResult("Data added successfully");  
  }  
 })  
 .addOnFailureListener(new OnFailureListener() {  
  @Override  
  public void onFailure(@NonNull Exception e) {  
   toastResult("Error while adding the data : " + e.getMessage());  
  }  
 });
Here, we created a collection named “tasks” and we inserted the data with “task_name”. The add() method automatically generates and assigns a unique alphanumeric identifier to every document it creates. If you want your documents to have your own custom IDs instead, you must first manually create those documents by calling the document() method, which takes a unique ID string as its input. You can then populate the documents by calling the set() method, which, like the add method, expects a map as its only argument.
You can set user preferred document name instead of auto generated unique identifier using the following method
myDB.collection("tasks").document("user_preferred_id").set(data)  
The following figure shows the DB after inserting the data.
Android
READ DATA
You can read the collection of data from firestore using “addSnapShotListener”. The code explains how to read data from Cloud Firestore.
myDB.collection("tasks").document("user_preferred_id").set(data)myDB.collection("tasks").addSnapshotListener(new EventListener() {  
        @Override  
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {  
            if (e != null)  
                toastResult(e.getMessage());  
            list.clear();  
            for (DocumentSnapshot doc : documentSnapshots) {  
                list.add(doc.getString("task_name"));  
            }  
        }  
    });
UPDATE DATA
You can update the record in the collection if you know the name/Id of the document. The following code shows how to update the data. Map is used to update the data with the same in the document.
Map data = new HashMap<>();  
data.put("data", edtData.getText().toString());  
myDB.collection("myData").document("1").update(data)  
        .addOnSuccessListener(new OnSuccessListener() {  
            @Override  
            public void onSuccess(Void aVoid) {  
                toastResult("Data updated successfully");  
            }  
        })  
        .addOnCompleteListener(new OnCompleteListener() {  
            @Override  
            public void onComplete(@NonNull Task task) {  
                toastResult("Data update Completed");  
            }  
        })  
        .addOnFailureListener(new OnFailureListener() {  
            @Override  
            public void onFailure(@NonNull Exception e) {  
                toastResult("Error while updating the data : " + e.getMessage());  
            }  
        });
DELETE DATA
The existing data can be deleted from Firestore using delete() function. The following code shows how to implement the delete function.
myDB.collection("myData").document("1").delete()  
    .addOnSuccessListener(new OnSuccessListener() {  
        @Override  
        public void onSuccess(Void aVoid) {  
            toastResult("Data deleted successfully");  
        }  
    })  
    .addOnFailureListener(new OnFailureListener() {  
        @Override  
        public void onFailure(@NonNull Exception e) {  
            toastResult("Error while deleting the data : " + e.getMessage());  
        }  
    });
Download Code
If you think this article is informative do like and star the repo in GitHub. You can download the full sample code here.
Demo
You can find the demo video on YouTube.

In this article, we will see how to create Live Templates in Android Studio or IntelliJ IDE products like WebStorm, PHPStorm, etc. Li...

How To Create Live Templates In Android Studio How To Create Live Templates In Android Studio

A blog about android developement


In this article, we will see how to create Live Templates in Android Studio or IntelliJ IDE products like WebStorm, PHPStorm, etc. Live Templates are very useful to increase the speed of development, efficiency, and accuracy.
Predefined Live Templates
Android Studio has some predefined live templates such as “psfi” which is a simplification of “private state final int”. The following are some additional predefined templates.
How to create your own Live Templates
We can create our own live templates using the following method.
  1. Open Android Studio and select File >> Settings as shown in Figure 1.

    Android
    Figure 1
  1. Now, the Settings popup is shown. Select Editor >> Live Templates. It lists the Live Templates categorized by their type or Languages as shown in Figure 2.

    Android
    Figure 2
  1. Then, select or click plus +.Select TemplateGroup and give a name for your Template Group as shown in Figure 3.

    Android
    Figure 3
  1. Select your Template Group and click plus +. Select Live Template and name your template, add your code and define your language like XML by selecting clicking Define like in Figure 4.

    Android
    Figure 4
  1. To use it, type the template abbreviation we have created and hit enter which replaces the code written in your template.
  2. Typing the abbreviation shows the template saved as shown in Figure 5 and hit Enter.

    Android
    Figure 5
  1. Which replaces the code typed by you.

    Android
We can do the same for all languages. This will increase the development speed, efficiency, and accuracy of code construction. If you like this article, do like and share and post your doubts in the comments section.

In this article, we will learn how to apply custom fonts to Views in Android like Toolbar, MenuItem apart from the views like TextView...

How to custom fonts to Views - Android How to custom fonts to Views - Android

A blog about android developement


In this article, we will learn how to apply custom fonts to Views in Android like Toolbar, MenuItem apart from the views like TextView, EditText.

FontUtils:

FontUtils is a tiny font utility library used to apply custom fonts to Views. It supports the following views.
  • Toolbar
  • NavigationView
  • Menu
  • Submenu
  • Other Views like EditText, TextView, etc.
This library is support the following Languages.
  • Android – Java
  • Android – Kotlin
  • Android

Coding Part:

Steps:

I have split this part into 3 steps as in the following.
Step 1: Creating New Project with Empty Activity.
Step 2: Setting up the Library for Android Views.
Step 3: Applying Custom fonts to Android Views.

Step 1:Creating New Project with Empty Activity

  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and select Empty activity.
  3. Click “finish” button to create new project in Android Studio.

Step 2:Setting up the Library for Android Views

In this part, we will see how to setup the library for the project.
  1. Open your app level build.gradle file and add the following lines to download the library.
    …
    implementation 'com.ajts.androidmads.fontutils:fontutils:1.0.1'
    …
    
  2. Then Click “Sync Now” to download the library.
  3. We need to use “compile” instead of “implementation” if we have using Android Studio Version below 3.0.

Step 3:Applying Custom fonts to Android Views

In this part, we will see how to apply custom fonts to Views. Here, we have to use “Typeface” and to more about “TypeFace” Click here.
  1. In this article, I am assigning the fonts from Assets folder. To create assets folder, right on the app folder and select New. Then select Folder and click assets folder.
  2. Then Copy and Paste the fonts you want to use with your application.
  3. The following line shows how to initialize the library.
    // Applying Custom Font
    Typeface typeface = Typeface.createFromAsset(getAssets(), "custom_font.ttf");
    // Init Library
    FontUtils fontUtils = new FontUtils();
  4. Then Initialize your Views and apply the fonts to the Views. The following example shows how to apply the fonts to Toolbar of your application.
    // Apply font to Toolbar
    fontUtils.applyFontToToolbar(toolbar, typeface);
  5. You can apply custom fonts to other views like NavigationView, Menu, Submenu, TextView like in following example.
    // Apply font to NavigationView
    fontUtils.applyFontToNavigationView(navigationView, typeface);
    // Apply font to Menu
    fontUtils.applyFontToMenu(menu, typeface);
    // Apply font to Other Views like TextView...
    fontUtils.applyFontToView(textview, typeface);
    fontUtils.applyFontToView(editText, typeface);
    fontUtils.applyFontToView(radioButton, typeface);
    fontUtils.applyFontToView(checkBox, typeface);

For Kotlin

We need to do the same steps mentioned. But we need to include Kotlin support while creating the project. Apply font to Views in Kotlin as show below.
// Applying Custom Font
val typeface = Typeface.createFromAsset(assets, "custom_font.ttf")
// Init Library
val fontUtils = FontUtils()
// Apply font to Toolbar
fontUtils.applyFontToToolbar(toolbar, typeface)
// Apply font to NavigationView
fontUtils.applyFontToNavigationView(navigationView, typeface)
// Apply font to Menu
fontUtils.applyFontToMenu(menu, typeface)
// Apply font to Other Views like TextView...
fontUtils.applyFontToView(textview, typeface)
fontUtils.applyFontToView(editText, typeface)
fontUtils.applyFontToView(radioButton, typeface)
fontUtils.applyFontToView(checkBox, typeface)

For Xamarin.Android

We can apply the same with Xamarin.Android. To know more Click Here.


Download Code

The article is informative do like and star the repo in GitHub. You can download the code here.
Note:
Java and Kotlin Android Support
https://github.com/androidmads/FontUtils
Xamarin.Android Support
https://github.com/Xamarin-Gists/XAFontUtilsLibrary

In this article, we will see some easiest way to reduce the APK Size of your application. The following methods discussed are very easy t...

How to Reduce the APK Size How to Reduce the APK Size

A blog about android developement

In this article, we will see some easiest way to reduce the APK Size of your application. The following methods discussed are very easy to do and remember.

1. Use Proguard:
Proguard is a code shrining tool used to reduce the APK size which removes the unused byte codes from the application and we need to take care after applying the Proguard.
Proguard can be enabled by changing “minifyEnabled” to true.
buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
Reference:

2. Use Lint:
Proguard is used to remove the unused byte code in Java side. But we need to make the same with our XML files. To achieve this, we can use Apache Lint and it can be run simply by calling
gradlew lint in your android studio’s terminal. It will generates an HTML report and shows the unused resources in the unused resources section. It will analyse the res directory of the application and not able access the assets directory of the application.

3. Use Vector Drawable:
Android supports Vector Drawable from the release of 23.2 support library and vector Drawable is an android version of SVG images in Android. We can convert SVG into Vector Drawable by Android Studio itself. It is small in size and colours can be changed by the image itself.
Reference:

4. Optimize PNG images:
Optimize the size of the PNG images used in the application. We can optimize the images using some online tools like OptiPng or TinyPng

5. Shrink Resources:
Using shrinkResources attribute in the Gradle will remove all the resources which are not being used anywhere in the project. We can add this within the release scope of your app level build.gradle.
buildTypes {
    release {
       …
        shrinkResources true
       …
    }
}

6. ResConfigs:
Remove the localized resources which are not needed by using resConfigs. As all the support libraries may have localized folders for the other languages which we don’t need.
defaultConfig {
...
  resConfigs "en", "hi"
...
}

7. Remove unused XML files:
You can make use of android-resource-remover is utility that removes unused resources reported by Android Lint from your project.

8. Remove Duplicates:
Use common functionalities and resources (or assets) to make code reusability and .reduce the line of coding.
For Example: Use colorFilter or tintMode to your ImageViews to avoid duplication of resources with different colours.

9. Remove Debug Libraries:
We recommend that you remove all debug-related functionality from the application. The application generally does not see or use this data, and the Android operating system does not require it to run the application. Hence, the debug information only wastes space, and should be removed.

10. Use Other Image Formats:
Android also supports WEBP images or 9-Patch Images. WEBP images are provides lossless compression rather than PNG or JPG images. WEBP supports from Android 3.2.

11. Use Methods Count Plugin:
Methods Count is an online tool used to the sizes of the libraries. Using this, we can find the alternative libraries with same functionality and less in method count.
Android Studio Plugin also available to do the same with the Android Studio IDE itself.

12. Use Facebook’s ReDex:
Optimize your final APK (after ProGuard) with Facebook’s ReDex. This should reduce the code size as well as potentially improve performance.
Reference:
Note: We can use Split APK method to reduce the size of the APK. But the above mentioned methods are simpler than this. To know more click here.

In this article, we will learn how to work with Alerts in Android using Kotlin. if you are new to Kotlin read my previous articles. This...

Alert Builder in Android -Kotlin Alert Builder in Android -Kotlin

A blog about android developement

In this article, we will learn how to work with Alerts in Android using Kotlin. if you are new to Kotlin read my previous articles. This article is very basic. But very worthier for learning from Scratch.
Implementing Alerts in Android using Kotlin is similar to Java implementation and so, it is very easy to understand. Here, we will learn the following alerts.
  1. Alert with two options.
  2. Alert with list.

Coding Part

I have split this article into 3 steps as follows:

Creating new Android Project with Kotlin in Android Studio 

By default, Android Studio 3.0 has the checkbox for Kotlin Support for your Android Application. Create new project in Android studio, check the Kotlin support, and start as usual with Android Studio 3.0.


For migrating Java Android Project to Kotlin Android Project, you can do the following processes.

Configuring Kotlin
Kotlin support can be configured by selecting Tools  Kotlin  Configure Kotlin. Then, Click “Sync Now”. This step is applicable to the Android Studio pre versions of 3.0. Best way is you must update your Android Studio.

In Android Studio 3.0, by default you have Kotlin Activity. For Android Studio with Version less than 3.0, can convert their Java activity into Kotlin Activity.

Open Quick Search or Click Ctrl + Shift + A for Windows Users and Search and Select “Convert Java to Kotlin” or simply Select Ctrl + Shift + Alt + K.

Adding User Interface in your Layout file 

In this step, we will add buttons for triggering normal alerts and list alerts. Open your activity_main.xml file and paste the following.
<?xml version="1.0" encoding="utf-8"?>  
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="com.ajts.androidmads.kotlinalerts.MainActivity"  
    tools:layout_editor_absoluteY="81dp">  
  
    <Button  
        android:id="@+id/optionAlert"  
        android:layout_width="0dp"  
        android:layout_height="wrap_content"  
        android:layout_marginTop="184dp"  
        android:text="Normal Alert"  
        app:layout_constraintEnd_toEndOf="@+id/listAlert"  
        app:layout_constraintStart_toStartOf="@+id/listAlert"  
        app:layout_constraintTop_toTopOf="parent"  
        android:onClick="showNormalAlert"/>  
  
    <Button  
        android:id="@+id/listAlert"  
        android:layout_width="123dp"  
        android:layout_height="wrap_content"  
        android:layout_marginTop="7dp"  
        android:text="List Alert"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toBottomOf="@+id/optionAlert"  
        android:onClick="showListAlert" />  
  
</android.support.constraint.ConstraintLayout>  
The Screen looks like the below screenshot.


Implementing the alerts in Kotlin 

Now open your Activity file and in my case, I am opening “MainActivity.kt”.
Show Alert Dialog with two options
fun showNormalAlert(v: View){  
    val dialog = AlertDialog.Builder(this).setTitle("Kotlin Study").setMessage("Alert Dialog")  
            .setPositiveButton("Confirm", { dialog, i ->  
                Toast.makeText(applicationContext, "Hello Friends", Toast.LENGTH_LONG).show()  
            })  
            .setNegativeButton("Cancel", { dialog, i -> })  
    dialog.show()  
} 
Showing List Type Alert Dialog
fun showListAlert(v: View){  
    val items = arrayOf("Android", "iOS", "Windows")  
    val dialog = AlertDialog.Builder(this).setTitle("Select your Mobile OS").setItems(items,  
            {  
                dialog, which ->  
                Toast.makeText(applicationContext, items[which], Toast.LENGTH_LONG).show();  
            })  
    dialog.show()  
}

Full Code

You can find the full code implementation below.
package com.ajts.androidmads.kotlinalerts  
  
import android.support.v7.app.AppCompatActivity  
import android.os.Bundle  
import android.support.v7.app.AlertDialog  
import android.view.View  
import android.widget.Toast  
  
class MainActivity : AppCompatActivity() {  
  
    override fun onCreate(savedInstanceState: Bundle?) {  
        super.onCreate(savedInstanceState)  
        setContentView(R.layout.activity_main)  
    }  
  
    fun showNormalAlert(v: View){  
        val dialog = AlertDialog.Builder(this).setTitle("Kotlin Study").setMessage("Alert Dialog")  
                .setPositiveButton("Confirm", { dialog, i ->  
                    Toast.makeText(this@MainActivity, "Hello Friends", Toast.LENGTH_LONG).show()  
                })  
                .setNegativeButton("Cancel", { dialog, i -> })  
        dialog.show()  
    }  
  
    fun showListAlert(v: View){  
        val items = arrayOf("Android", "iOS", "Windows")  
        val dialog = AlertDialog.Builder(this).setTitle("Select your Mobile OS").setItems(items,  
                {  
                    dialog, which ->  
                    Toast.makeText(applicationContext, items[which], Toast.LENGTH_LONG).show();  
                })  
        dialog.show()  
    }  
}
If this article is useful to you, do like it and keep on commenting if you have any clarifications.

Download Code: 

You can download sample code from the following GitHub link.

In this article, we will learn how to open Android Application from your browser or hyperlink, if it is installed in android phones. ...

Custom URL Scheme in Android Custom URL Scheme in Android

A blog about android developement

In this article, we will learn how to open Android Application from your browser or hyperlink, if it is installed in android phones.

Custom URL Scheme:

Custom URL Scheme is an awesome and interesting concept in android development. Using this method, user can open the android application from hyperlink. The implementation of this method is very simple. The same concept is available for iOS also.

Coding Part:

Steps
The implementation is split into 3 steps as in following.
Step 1: Creating New Project with Android Studio.
Step 2: Setting up AndroidManifest for the project
Step 3: Implementing the functionality to open the application.
Without any more introduction, we will jump into the coding part.

Step 1: Creating New Project with Android Studio:

1. Open Android Studio and Select Create new project.

2. Name the project as your wish and select your activity template.
3. Click “finish” button to create new project in Android Studio.
Step 2: Setting up AndroidManifest for the project:
This step is very important for the implementation of Custom URL Scheme. Here, you must specify the host and path of the URL Scheme
<intent-filter>
<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

<data
android:host="your_host"
android:scheme="your_scheme" />

</intent-filter>
You should specify your host and scheme name with Intent Filter in your AndroidManifest.xml file against an Activity. Without specifying the name of the activity, you can open particular Activity. The Intent Filter should have the following action and categories.
<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
The URL Scheme is looks like your_scheme://your_host For Example androidmad://post You can pass the query parameters through this URL to the application.
Ex: androidmad://post?post_id=1

Step 3: Implementing the functionality to open the application

In this step, we will see how to receive the data from the custom URL scheme. The URL is received using Intents.
Intent intent = getIntent();
if(Intent.ACTION_VIEW.equals(intent.getAction())){
Uri uri = intent.getData();
String post_id = uri.getQueryParameter("post_id");
}

Sample URI Calling method

You can call your Application’s activity from another like below
String  url =”selphone://post_detail?post_id=10";
Intent 
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);

Download Code:

You can download sample code from the following GitHub link.