Monday, February 29, 2016

How to run a PHP script with cron on Ubuntu (every 30 minutes)

For one of the customer, I wanted to execute a PHP script every 30 minutes automatically on Ubuntu. This can be achieved by setting up a cron job on Ubuntu. The same idea can be achieved on Windows by using the scheduler; see my previous post: Cron Job Creation for windows server to run PHP Script.

Prerequisites

  • PHP CLI installed (package often named php-cli or provided by the php package on modern Ubuntu). Verify with:
which php
php -v
  • The PHP script you want to run; make sure you use absolute paths in cron.
  • Basic access to the user account that will run the cron job.

Make the script executable (optional)

If you want to run the script directly (instead of calling the php binary), add a shebang to the top of your PHP file and make it executable.

Example shebang (adjust path if which php shows a different location):

#!/usr/bin/php
<?php
// your code

Make the script executable:

chmod +x /path/to/script.php

Open a terminal

On most Ubuntu desktop systems press Alt+Ctrl+T to open a terminal.

Edit the crontab

Run:

crontab -e

This opens your user's crontab in the editor. Add a line to run the script every 30 minutes.

Example: call PHP binary and script with absolute paths

0,30 * * * * /usr/local/bin/php /home/username/public_html/export.php

This example is taken from the original post. Ensure /usr/local/bin/php is the correct PHP CLI path on your system (use which php to confirm). If which php prints /usr/bin/php, use that instead.

Alternative: run the script directly (with shebang)

If your script is executable and has the correct shebang, you can call it directly:

0,30 * * * * /home/username/public_html/export.php

Cron schedule explanation

A cron line has five time fields followed by the command:

minute hour day-of-month month day-of-week command

0,30 * * * * means "at minute 0 and 30 of every hour, every day" (i.e., every 30 minutes).

Recommended improvements for reliability

  • Always use absolute paths for the PHP binary and the script.
  • Cron runs with a minimal environment — do not rely on shell environment variables unless you set them in the crontab.
  • If your script references files or other executables, use absolute paths for those too.
  • Capture output and errors to a log file to help debugging:
0,30 * * * * /usr/bin/php /home/username/public_html/export.php >> /home/username/logs/export.log 2>&1
  • If you need particular environment variables (PATH, HOME, etc.), set them at the top of the crontab:
PATH=/usr/local/bin:/usr/bin:/bin
SHELL=/bin/bash

Troubleshooting

  • Verify the crontab entry exists:
crontab -l
  • Test the command manually from the same user account:
/usr/bin/php /home/username/public_html/export.php
  • Check cron logs. On many Ubuntu systems:
# syslog (older setups)
grep CRON /var/log/syslog

# systemd-based systems
journalctl -u cron
  • Ensure file permissions: the user running the cron job must have execute/read access to the script and any resources it uses.

Further reading / help

For more information about crontab run:

crontab --help
man crontab

That's it. Happy Coding!!!

Saturday, February 27, 2016

How to Add a Music Player to Blogspot (Blogger) — HTML5 Audio + Hosting

While composing the blog, you can write the content of the blog normally. Then place your cursor where you want to add the audio player. Then use any of the below methods:

1. Using Basic HTML5 Tags

The

Here's a basic example using the

<audio controls>
  <source src="url-of-audio-file" />
  If you cannot see the audio controls, your browser does not support the audio element
</audio>

Notes on the example above:

  • The controls attribute displays a simple player so visitors can start/stop playback and adjust volume.
  • If you want the audio to play automatically, add autoplay (but read the autoplay note below).

Autoplay example:

<audio controls autoplay>
  <source src="url-of-audio-file" />
  If you cannot see the audio controls, your browser does not support the audio element
</audio>

Loop example:

<audio controls loop>
  <source src="url-of-audio-file" />
  If you cannot see the audio controls, your browser does not support the audio element
</audio>

Improved (recommended) cross-browser example with multiple sources and a downloadable fallback link:

<audio controls aria-label="Blog post audio" style="max-width:100%;">
  <source src="https://example.com/audio-file.mp3" type="audio/mpeg">
  <source src="https://example.com/audio-file.ogg" type="audio/ogg">
  Your browser does not support the audio element. Listen/download the audio file here: <a href="https://example.com/audio-file.mp3">audio-file.mp3</a>
</audio>
  • Include type attributes when possible so browsers can pick the best source.
  • Add an aria-label or visible caption for screen readers.

Autoplay note: modern browsers often block autoplay with sound. Autoplay may only work if the audio is muted or if the user has previously interacted with the site. For best UX and fewer compatibility issues, keep controls and avoid forcing autoplay.

2. Hosting files for the Audio Player

Blogger does not let you upload arbitrary audio files to post storage. You must host the mp3/audio files somewhere that provides a direct (raw) HTTPS URL. Some options and considerations:

  • Dropbox: In the past you could use Dropbox direct links; however, Dropbox changed how sharing links work and you often need to convert the shared link into a direct raw link (or use Dropbox Business/hosted sites). Test the link to ensure it streams directly in a browser.
  • Google Sites / Google Drive: Google Drive direct linking is fragile and not recommended for production hosting. The article's earlier linked post shows a technique for uploads — keep that link and verify the resulting URLs.
  • Recommended approach: host audio on any static file host that gives a direct HTTPS URL (GitHub Pages, Amazon S3, Cloudflare Workers/Pages, your web host, or any storage provider that returns a raw file URL). The key requirement is a direct URL that returns the audio file (not an HTML preview page).

Once you have uploaded your audio files, make a note of the direct link to the file which you'll add as the src in the audio player code.

Verify the hosting works by opening the audio URL directly in a new private/incognito tab. You should see the audio stream or download as an audio file (not an HTML page).

3. Using the Code Generator Below

Be sure to check the "Interpret Typed HTML" option on the post Options in the right side of the post editor, otherwise the raw code for your player will be displayed instead. Or switch to the post HTML view and paste the code generated.

If you prefer a small generator on this page that builds the

Generate code for audio player
Preview of audio player will appear here

How to insert into Blogger (step-by-step)

  1. Open your Blogger post editor.
  2. Place the cursor where you want the audio player to appear.
  3. Switch to HTML view (or enable "Interpret Typed HTML" in the post Options) and paste the audio markup (one of the code blocks above).
  4. Switch back to Compose to see how it looks (preview in a new browser tab or publish to test).
  5. Test on mobile and desktop browsers.

Accessibility and mobile considerations

  • Keep controls visible so users can control playback on mobile.
  • Add aria-label="..." and a text fallback link so screen reader users can access the audio.
  • Avoid autoplay with sound — it can be intrusive and will often be blocked.

Troubleshooting

  • No audio controls shown: Ensure the audio markup was pasted into HTML mode and not escaped as text. Also confirm the browser supports the audio format.
  • 404 or access denied: The audio src is not a direct public URL or is blocked by CORS. Host the file on a server that provides public file access (HTTPS) or fix permissions.
  • Browser blocks autoplay: Remove autoplay or use muted autoplay only (not recommended for music).
  • Formats not supported: Provide multiple source formats (.mp3, .ogg) to maximize browser compatibility.

References

Sunday, February 7, 2016

VBA Macro: Copy Data from One Workbook to Another (without manual open)

One of my friend was trying to copy the data from one work book to other workbook. We can automate this using the VB macro. Here is the solution for it.

Overview

This post shows a simple VBA macro that opens two example workbooks, copies a range from each, and pastes the data into a report workbook. The example keeps the author's original code and example files so you can reproduce the result.

Prerequisites

  • Excel with VBA support (desktop Excel). The report workbook must be saved as a macro-enabled workbook (Report.xlsm) to store the macro.
  • The macro uses explicit file paths in the example; update the paths to match your system.

Example files and screenshots

Original workbook (test1.xlsx) contents:

test1 screenshot

You can download it from here: test1.xlsx

Second workbook (test2.xlsx) contents:

test2 screenshot

You can download it from here: test2.xlsx

Report workbook (expected result):

report screenshot

You can download the report (contains the macro) from here: report.xlsm

VBA macro (copy and paste into a module named test)

Use the macro below exactly as provided by the author. Update the file paths if needed.

Sub test()

Application.ScreenUpdating = False
Workbooks.Open Filename:="F:\Projects\freelancer\vba\test1.xlsx"
'For I = 1 To 50
 Workbooks("test1.xlsx").Sheets("Sheet1").Range("B2:B15").Copy
 Workbooks("Report.xlsm").Sheets("Sheet1").Range("B2").PasteSpecial
    'Workbooks("Report.xlsm").ActiveSheet.Range("B2:B15").Value = Workbooks("test1.xlsx").Sheets("Sheet1").Range("B2:B15")
'Next I
Windows("test1.xlsx").Close

 Workbooks.Open Filename:="F:\Projects\freelancer\vba\test2.xlsx"
 Workbooks("test2.xlsx").Sheets("Sheet1").Range("B2:B15").Copy
 Workbooks("Report.xlsm").Sheets("Sheet1").Range("C2").PasteSpecial
Windows("test2.xlsx").Close

Application.ScreenUpdating = True
 Workbooks("Report.xlsm").Save
End Sub

How it works (brief)

  • The macro turns off ScreenUpdating to speed execution.
  • It opens test1.xlsx, copies B2:B15 from Sheet1, and pastes into B2 of Report.xlsm.
  • It closes test1.xlsx, then opens test2.xlsx and copies B2:B15 into C2 of Report.xlsm.
  • Finally it re-enables ScreenUpdating and saves Report.xlsm.

The author commented an alternative approach that assigns values directly instead of Copy/PasteSpecial:

'Workbooks("Report.xlsm").ActiveSheet.Range("B2:B15").Value = Workbooks("test1.xlsx").Sheets("Sheet1").Range("B2:B15")

That approach avoids the clipboard and is generally faster for value-only transfers.

Notes, fixes, and recommendations

  • Typos in the original text: "VB Micro" should read "VBA macro"; "xlx" appears where "xlsx" or "xls" is intended. Fix these for clarity.
  • Paths: replace the example paths (F:\Projects...) with your actual file locations. Use double backslashes in VBA string literals or single forward slashes.
  • Use explicit workbook variables for safer code. For example:
Dim wbSrc As Workbook, wbReport As Workbook
Set wbReport = Workbooks("Report.xlsm")
Set wbSrc = Workbooks.Open("C:\path\test1.xlsx")
wbSrc.Sheets("Sheet1").Range("B2:B15").Copy wbReport.Sheets("Sheet1").Range("B2")
wbSrc.Close False
  • Avoid Windows("name").Close when workbooks may have different window captions; prefer wb.Close.
  • Consider using PasteSpecial arguments, e.g., PasteSpecial xlPasteValues if you only need values.
  • Add basic error handling around file opens and saves to catch missing files or permission issues.

Troubleshooting

  • "Subscript out of range": usually the workbook or sheet name is wrong. Confirm filenames and sheet names match exactly.
  • "Path not found" or "File not found": update the Filename path to the correct location.
  • Macro not running: ensure macros are enabled and Report.xlsm is macro-enabled.

That's it. Happy coding.

Thursday, February 4, 2016

How to Add Automatic SMS OTP Verification to Android Apps (WhatsApp‑style) — Part II

In continuation with my previous blog Adding SMS Verification Like WhatsApp to Android Application Part-I, here I continue with the implementation details for automatic SMS OTP verification. This part shows the BroadcastReceiver, IntentService, layouts, manifest changes and the registration screen.

TL;DR

  • The article contains the core runnable code for: HttpService (network call to verify OTP), SmsReceiver (reads incoming SMS and extracts OTP), SmsActivity (UI to request SMS and enter OTP manually), and MainActivity (post-login screen).
  • Important: For modern Android you should read the "Android versions & security" section below before copying the code: runtime permissions, SMS Retriever/User Consent APIs and background execution limits are not covered by the original code and must be added for Android 6+ and Android 8+.

1. HttpService.java (service directory)

This IntentService receives an OTP string via intent extras and posts it to the server to verify and activate the user. The code uses Volley for network requests and PrefManager to store the user profile on success.

Code (copy into service/HttpService.java):

package marutsoft.com.smsverify.service;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import marutsoft.com.smsverify.activity.MainActivity;
import marutsoft.com.smsverify.app.Config;
import marutsoft.com.smsverify.app.MyApplication;
import marutsoft.com.smsverify.helper.PrefManager;

/**
 * Created by Karjol G T on 01-02-2016.
 */
public class HttpService extends IntentService {

    private static String TAG = HttpService.class.getSimpleName();

    public HttpService() {
        super(HttpService.class.getSimpleName());
    }

    @Override    
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            String otp = intent.getStringExtra("otp");
            verifyOtp(otp);
        }
    }

    /**
     * Posting the OTP to server and activating the user
     *
     * @param otp otp received in the SMS
     */    
    private void verifyOtp(final String otp) {
        StringRequest strReq = new StringRequest(Request.Method.POST,

                Config.URL_VERIFY_OTP, new Response.Listener<String>() {

            @Override            
            public void onResponse(String response) {
                Log.d(TAG, response.toString());

                try {

                    JSONObject responseObj = new JSONObject(response);
                    Toast.makeText(getApplicationContext(), responseObj.toString(), Toast.LENGTH_LONG).show();
                    // Parsing json object response
                    // response will be a json object
                    boolean error = responseObj.getBoolean("error");
                    String message = responseObj.getString("message");

                    if (!error) {
                        // parsing the user profile information                     
                        JSONObject profileObj = responseObj.getJSONObject("profile");

                        String name = profileObj.getString("name");
                        String email = profileObj.getString("email");
                        String mobile = profileObj.getString("mobile");

                        PrefManager pref = new PrefManager(getApplicationContext());
                        pref.createLogin(name, email, mobile);

                        Intent intent = new Intent(HttpService.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);

                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();

                    } else {
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    Toast.makeText(getApplicationContext(),
                            "Error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override            
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {

            @Override            
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("otp", otp);

                Log.e(TAG, "Posting params: " + params.toString());
                return params;
            }

        };

        // Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(strReq);
    }

}

Note: avoid logging or Toasting the OTP in production (this code uses them for debugging). Also consider replacing IntentService with JobIntentService / WorkManager for Android O+ background restrictions (see "Android versions & security" below).


2. SmsReceiver.java (receiver directory)

This BroadcastReceiver listens for incoming SMS messages, filters by origin, extracts the OTP using a delimiter, and starts HttpService with the OTP.

Code (copy into receiver/SmsReceiver.java):

package marutsoft.com.smsverify.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import marutsoft.com.smsverify.app.Config;
import marutsoft.com.smsverify.service.HttpService;

/**
 * Created by Karjol G T on 01-02-2016.
 */public class SmsReceiver extends BroadcastReceiver {

    private static final String TAG = SmsReceiver.class.getSimpleName();

    @Override    
    public void onReceive(Context context, Intent intent) {

        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {
                Object[] pdusObj = (Object[]) bundle.get("pdus");
                for (Object aPdusObj : pdusObj) {
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) aPdusObj);
                    String senderAddress = currentMessage.getDisplayOriginatingAddress();
                    String message = currentMessage.getDisplayMessageBody();

                    Log.e(TAG, "Received SMS: " + message + ", Sender: " + senderAddress);

                    // if the SMS is not from our gateway, ignore the message                   
                    if (!senderAddress.toLowerCase().contains(Config.SMS_ORIGIN.toLowerCase())) {
                        return;
                    }

                    // verification code from sms                    
                    String verificationCode = getVerificationCode(message);

                    Log.e(TAG, "OTP received: " + verificationCode);

                    Intent hhtpIntent = new Intent(context, HttpService.class);
                    hhtpIntent.putExtra("otp", verificationCode);
                    context.startService(hhtpIntent);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }

    /**
     * Getting the OTP from sms message body
     * ':' is the separator of OTP from the message
     *
     * @param message     
    * @return     
    */    
    private String getVerificationCode(String message) {
        String code = null;
        int index = message.indexOf(Config.OTP_DELIMITER);

        if (index != -1) {
            int start = index + 2;
            int length = 6;
            code = message.substring(start, start + length);
            return code;
        }

        return code;
    }

}

Important robustness and API notes (you should apply these to the above code):

  • Use Telephony.Sms.Intents.getMessagesFromIntent(intent) to get SmsMessage[] which handles multipart PDUs and format differences.
  • For API >= 23 use SmsMessage.createFromPdu(byte[] pdu, String format) if you must call createFromPdu.
  • Validate bounds before substringing the OTP: ensure start + length <= message.length().
  • Avoid logging or Toasting the OTP (sensitive information).

3. AndroidManifest.xml changes

Add required permissions and register the receiver and service. The original manifest snippets:

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

And inside <application> (excerpt):

<application android:name=".app.MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme">

    <activity android:name=".activity.SmsActivity" android:label="@string/title_activity_sms">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".activity.MainActivity" android:label="@string/app_name" android:windowSoftInputMode="adjustResize" />

    <!-- SMS Receiver -->
    <receiver android:name=".receiver.SmsReceiver">
      <intent-filter android:priority="99999">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
      </intent-filter>
    </receiver>

    <!-- Intent service -->
    <service android:name=".service.HttpService" android:exported="false" />

</application>

Notes & cautions:

  • Runtime permissions: RECEIVE_SMS and READ_SMS require requesting the permission at runtime on Android 6+. Add code in your activity to request and handle user response.
  • Very high receiver priority is discouraged; it can block other SMS handlers. Consider lowering priority or using SMS Retriever / User Consent to avoid requiring READ_SMS.
  • On Android 8+ you cannot reliably start background services from a receiver; consider JobIntentService or WorkManager.

4. activity_sms.xml (res/layout)

Create the registration / verification screens. The original layout is long; include it as given:

<!-- activity_sms.xml content -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/viewContainer" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="marutsoft.com.smsverify.activity.SmsActivity">

    <marutsoft.com.smsverify.helper.MyViewPager        android:id="@+id/viewPagerVertical"        android:layout_width="fill_parent"        android:layout_height="fill_parent">

        <LinearLayout            android:id="@+id/layout_sms"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:background="@color/colorPrimary"            android:gravity="center_horizontal"            android:orientation="vertical">

            <ImageView                android:layout_width="60dp"                android:layout_height="60dp"                android:layout_gravity="center_horizontal"                android:layout_marginBottom="25dp"                android:layout_marginTop="100dp"                android:src="@mipmap/ic_launcher" />

            <TextView                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_marginBottom="25dp"                android:gravity="center_horizontal"                android:inputType="textCapWords"                android:paddingLeft="40dp"                android:paddingRight="40dp"                android:text="@string/msg_enter_mobile"                android:textColor="@android:color/white"                android:textSize="14dp" />

            <LinearLayout                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:orientation="vertical">

                <EditText                    android:id="@+id/inputName"                    android:layout_width="fill_parent"                    android:layout_height="wrap_content"                    android:layout_marginBottom="15dp"                    android:background="@android:color/white"                    android:fontFamily="sans-serif-light"                    android:hint="@string/lbl_name"                    android:padding="5dp"                    android:singleLine="true"                    android:textColor="@color/colorPrimary"                    android:textSize="18dp" />

                <EditText                    android:id="@+id/inputEmail"                    android:layout_width="fill_parent"                    android:layout_height="wrap_content"                    android:layout_marginBottom="15dp"                    android:background="@android:color/white"                    android:fontFamily="sans-serif-light"                    android:hint="@string/lbl_email"                    android:inputType="textEmailAddress"                    android:padding="5dp"                    android:textColor="@color/colorPrimary"                    android:textSize="18dp" />

                <EditText                    android:id="@+id/inputMobile"                    android:layout_width="240dp"                    android:layout_height="wrap_content"                    android:background="@android:color/white"                    android:fontFamily="sans-serif-light"                    android:hint="@string/lbl_mobile"                    android:inputType="phone"                    android:maxLength="10"                    android:padding="5dp"                    android:textColor="@color/colorPrimary"                    android:textCursorDrawable="@null"                    android:textSize="18dp" />

                <Button                    android:id="@+id/btn_request_sms"                    android:layout_width="fill_parent"                    android:layout_height="wrap_content"                    android:layout_gravity="center_horizontal"                    android:layout_marginTop="25dp"                    android:background="@color/colorPrimaryDark"                    android:text="@string/lbl_next"                    android:textColor="@android:color/white"                    android:textSize="14dp" />
            </LinearLayout>


        </LinearLayout>

        <LinearLayout            android:id="@+id/layout_otp"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:background="@color/colorPrimary"            android:gravity="center_horizontal"            android:orientation="vertical">

            <ImageView                android:layout_width="60dp"                android:layout_height="60dp"                android:layout_gravity="center_horizontal"                android:layout_marginBottom="25dp"                android:layout_marginTop="100dp"                android:src="@mipmap/ic_launcher" />

            <TextView                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_marginBottom="15dp"                android:gravity="center_horizontal"                android:paddingLeft="40dp"                android:paddingRight="40dp"                android:text="@string/msg_sit_back"                android:textColor="@android:color/white"                android:textSize="16dp" />

            <TextView                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_marginBottom="25dp"                android:gravity="center_horizontal"                android:paddingLeft="40dp"                android:paddingRight="40dp"                android:text="@string/msg_manual_otp"                android:textColor="@android:color/white"                android:textSize="12dp" />

            <EditText                android:id="@+id/inputOtp"                android:layout_width="120dp"                android:layout_height="wrap_content"                android:background="@android:color/white"                android:fontFamily="sans-serif-light"                android:gravity="center_horizontal"                android:hint="@string/lbl_enter_otp"                android:inputType="number"                android:maxLength="6"                android:padding="10dp"                android:textCursorDrawable="@null"                android:textSize="18dp" />

            <Button                android:id="@+id/btn_verify_otp"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="center_horizontal"                android:layout_marginTop="25dp"                android:background="@color/colorPrimaryDark"                android:paddingLeft="20dp"                android:paddingRight="20dp"                android:text="@string/lbl_submit"                android:textColor="@android:color/white"                android:textSize="14dp" />

        </LinearLayout>

    </marutsoft.com.smsverify.helper.MyViewPager>

    <ProgressBar        android:id="@+id/progressBar"        android:layout_width="30dp"        android:layout_height="30dp"        android:layout_alignParentBottom="true"        android:layout_centerHorizontal="true"        android:layout_gravity="center"        android:layout_marginBottom="60dp"        android:indeterminateTint="@color/colorAccent"        android:indeterminateTintMode="src_atop"        android:visibility="gone" />

    <LinearLayout        android:id="@+id/layout_edit_mobile"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:layout_marginBottom="50dp"        android:gravity="center"        android:orientation="horizontal">

        <TextView            android:id="@+id/txt_edit_mobile"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textColor="@android:color/white"            android:textSize="16dp" />

        <ImageButton            android:id="@+id/btn_edit_mobile"            android:layout_width="40dp"            android:layout_height="40dp"            android:layout_marginLeft="10dp"            android:background="@null"            android:src="@drawable/ic_edit_mobile" />
    </LinearLayout>

</RelativeLayout>

Add content descriptions (android:contentDescription) for images and ensure labels are present for accessibility.


5. SmsActivity.java (activity directory)

This activity shows the registration screen, requests an OTP from the server, and allows manual OTP entry. It also starts HttpService with the entered OTP.

Code (copy into activity/SmsActivity.java):

package marutsoft.com.smsverify.activity;

import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import marutsoft.com.smsverify.R;
import marutsoft.com.smsverify.app.Config;
import marutsoft.com.smsverify.app.MyApplication;
import marutsoft.com.smsverify.helper.PrefManager;
import marutsoft.com.smsverify.service.HttpService;

/**
 * Created by Karjol G T on 02-02-2016.
 */public class SmsActivity extends AppCompatActivity implements View.OnClickListener {

    private static String TAG = SmsActivity.class.getSimpleName();

    private ViewPager viewPager;
    private ViewPagerAdapter adapter;
    private Button btnRequestSms, btnVerifyOtp;
    private EditText inputName, inputEmail, inputMobile, inputOtp;
    private ProgressBar progressBar;
    private PrefManager pref;
    private ImageButton btnEditMobile;
    private TextView txtEditMobile;
    private LinearLayout layoutEditMobile;


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

        viewPager = (ViewPager) findViewById(R.id.viewPagerVertical);
        inputName = (EditText) findViewById(R.id.inputName);
        inputEmail = (EditText) findViewById(R.id.inputEmail);
        inputMobile = (EditText) findViewById(R.id.inputMobile);
        inputOtp = (EditText) findViewById(R.id.inputOtp);
        btnRequestSms = (Button) findViewById(R.id.btn_request_sms);
        btnVerifyOtp = (Button) findViewById(R.id.btn_verify_otp);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        btnEditMobile = (ImageButton) findViewById(R.id.btn_edit_mobile);
        txtEditMobile = (TextView) findViewById(R.id.txt_edit_mobile);
        layoutEditMobile = (LinearLayout) findViewById(R.id.layout_edit_mobile);

        // view click listeners        
        btnEditMobile.setOnClickListener(this);
        btnRequestSms.setOnClickListener(this);
        btnVerifyOtp.setOnClickListener(this);

        // hiding the edit mobile number        
        layoutEditMobile.setVisibility(View.GONE);

        pref = new PrefManager(this);

        // Checking for user session        // if user is already logged in, take him to main activity        
        if (pref.isLoggedIn()) {
            Intent intent = new Intent(SmsActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);

            finish();
        }

        adapter = new ViewPagerAdapter();
        viewPager.setAdapter(adapter);
        //viewPager.setOnP        
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override            
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override            
            public void onPageSelected(int position) {
            }

            @Override            
            public void onPageScrollStateChanged(int state) {

            }
        });


        /**         * Checking if the device is waiting for sms         * showing the user OTP screen         */        
        if (pref.isWaitingForSms()) {
            viewPager.setCurrentItem(1);
            layoutEditMobile.setVisibility(View.VISIBLE);
        }
    }

    @Override    
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_request_sms:
                validateForm();
                break;

            case R.id.btn_verify_otp:
                verifyOtp();
                break;

            case R.id.btn_edit_mobile:
                viewPager.setCurrentItem(0);
                layoutEditMobile.setVisibility(View.GONE);
                pref.setIsWaitingForSms(false);
                break;
        }
    }

    /**     * Validating user details form     */    
    private void validateForm() {
        String name = inputName.getText().toString().trim();
        String email = inputEmail.getText().toString().trim();
        String mobile = inputMobile.getText().toString().trim();

        // validating empty name and email        
        if (name.length() == 0 || email.length() == 0) {
            Toast.makeText(getApplicationContext(), "Please enter your details", Toast.LENGTH_SHORT).show();
            return;
        }

        // validating mobile number        // it should be of 10 digits length        
        if (isValidPhoneNumber(mobile)) {

            // request for sms            
            progressBar.setVisibility(View.VISIBLE);

            // saving the mobile number in shared preferences            
            pref.setMobileNumber(mobile);

            // requesting for sms            
            requestForSMS(name, email, mobile);

        } else {
            Toast.makeText(getApplicationContext(), "Please enter valid mobile number", Toast.LENGTH_SHORT).show();
        }
    }

    /**     * Method initiates the SMS request on the server     *
     * @param name   user name     * @param email  user email address     * @param mobile user valid mobile number     */    
    private void requestForSMS(final String name, final String email, final String mobile) {
        StringRequest strReq = new StringRequest(Request.Method.POST,
                Config.URL_REQUEST_SMS, new Response.Listener<String>() {

            @Override            
            public void onResponse(String response) {
                Log.d(TAG, response.toString());

                try {
                    JSONObject responseObj = new JSONObject(response);

                    // Parsing json object response                    // response will be a json object                    
                    boolean error = responseObj.getBoolean("error");
                    String message = responseObj.getString("message");

                    // checking for error, if not error SMS is initiated                    // device should receive it shortly                    
                    if (!error) {
                        // boolean flag saying device is waiting for sms                        
                        pref.setIsWaitingForSms(true);

                        // moving the screen to next pager item i.e otp screen                        
                        viewPager.setCurrentItem(1);
                        txtEditMobile.setText(pref.getMobileNumber());
                        layoutEditMobile.setVisibility(View.VISIBLE);

                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();

                    } else {
                        Toast.makeText(getApplicationContext(),
                                "Error: " + message,
                                Toast.LENGTH_LONG).show();
                    }

                    // hiding the progress bar                    
                    progressBar.setVisibility(View.GONE);

                } catch (JSONException e) {
                    Toast.makeText(getApplicationContext(),
                            "Error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();

                    progressBar.setVisibility(View.GONE);
                }

            }
        }, new Response.ErrorListener() {

            @Override            
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
            }
        }) {

            /**             * Passing user parameters to our server             *             */            
            @Override            
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("mobile", mobile);

                Log.e(TAG, "Posting params: " + params.toString());

                return params;
            }

        };

        // Adding request to request queue        
        MyApplication.getInstance().addToRequestQueue(strReq);
    }

    /**     * sending the OTP to server and activating the user     */    
    private void verifyOtp() {
        String otp = inputOtp.getText().toString().trim();

        if (!otp.isEmpty()) {
            Intent grapprIntent = new Intent(getApplicationContext(), HttpService.class);
            grapprIntent.putExtra("otp", otp);
            startService(grapprIntent);
        } else {
            Toast.makeText(getApplicationContext(), "Please enter the OTP", Toast.LENGTH_SHORT).show();
        }
    }

    /**     * Regex to validate the mobile number     * mobile number should be of 10 digits length     *
     * @param mobile     * @return     */    
    private static boolean isValidPhoneNumber(String mobile) {
        String regEx = "^[0-9]{10}$";
        return mobile.matches(regEx);
    }


    class ViewPagerAdapter extends PagerAdapter {

        @Override        
        public int getCount() {
            return 2;
        }

        @Override        
        public boolean isViewFromObject(View view, Object object) {
            return view == ((View) object);
        }

        public Object instantiateItem(View collection, int position) {

            int resId = 0;
            switch (position) {
                case 0:
                    resId = R.id.layout_sms;
                    break;
                case 1:
                    resId = R.id.layout_otp;
                    break;
            }
            return findViewById(resId);
        }
    }


}

Notes: Add runtime permission request flow before attempting to read SMS or register the receiver.


6. Toolbar layout (res/layout/toolbar.xml)

Toolbar XML used by MainActivity:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:local="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="?attr/actionBarSize" android:background="?attr/colorPrimary" local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

7. activity_main.xml (layout for the logged in screen)

Original code for the main activity layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

    <LinearLayout        android:id="@+id/layout_toolbar"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:orientation="vertical">

        <include            android:id="@+id/toolbar"            layout="@layout/toolbar" />
    </LinearLayout>

    <LinearLayout        android:id="@+id/layout_mobile"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:orientation="vertical">

        <TextView            android:id="@+id/name"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:padding="10dp"            android:textSize="18dp" />

        <TextView            android:id="@+id/email"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:padding="10dp"            android:textSize="18dp" />

        <TextView            android:id="@+id/mobile"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:padding="10dp"            android:textSize="18dp" />

    </LinearLayout>
</RelativeLayout>

8. menu_main.xml (menu)

Menu contains a logout action:

<menu 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" tools:context=".MainActivity">
  <item        android:id="@+id/action_logout"        android:orderInCategory="100"        android:title="@string/action_logout"        app:showAsAction="always" />
</menu>

9. MainActivity.java (showing stored profile and logout)

Code (copy into activity/MainActivity.java):

package marutsoft.com.smsverify.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import java.util.HashMap;

import marutsoft.com.smsverify.R;
import marutsoft.com.smsverify.helper.PrefManager;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private PrefManager pref;
    private TextView name, email, mobile;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        name = (TextView) findViewById(R.id.name);
        email = (TextView) findViewById(R.id.email);
        mobile = (TextView) findViewById(R.id.mobile);

        // enabling toolbar        
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);


        pref = new PrefManager(getApplicationContext());


        // Checking if user session        // if not logged in, take user to sms screen        
        if (!pref.isLoggedIn()) {
            logout();
        }

        // Displaying user information from shared preferences        
        HashMap<String, String> profile = pref.getUserDetails();
        name.setText("Name: " + profile.get("name"));
        email.setText("Email: " + profile.get("email"));
        mobile.setText("Mobile: " + profile.get("mobile"));
    }

    /**     * Logging out user     * will clear all user shared preferences and navigate to     * sms activation screen     */    
    private void logout() {
        pref.clearSession();

        Intent intent = new Intent(MainActivity.this, SmsActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        startActivity(intent);

        finish();
    }


    @Override    
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override    
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement       
        if (id == R.id.action_logout) {
            logout();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

10. Run and test

With proper configuration in Config.java (URLs for URL_REQUEST_SMS and URL_VERIFY_OTP) and a server endpoint that sends OTP via SMS to the supplied mobile number, you can run the application and test sign‑up and OTP verification.

screenshot

That's it. Happy Coding


Android versions & security (must read before copying the code)

  • Android 6 (Marshmallow) and above: READSMS and RECEIVESMS are runtime permissions. You must request them in the Activity and handle the user's decision. If the user denies, fall back to manual OTP entry.
  • Android 8 (Oreo) and above: apps cannot freely start background services from a BroadcastReceiver. Replace IntentService with JobIntentService or schedule work with WorkManager for network calls triggered from a receiver.
  • SMS Retriever API / SMS User Consent API: to avoid asking for SMS reading permissions and to comply with Play policy, prefer the SMS Retriever API or the User Consent API. These allow auto‑retrieval of OTP without READ_SMS.
  • Privacy & security: never log or display the OTP in Toasts or logs in production. Always use HTTPS for server requests and verify OTP server‑side. Add rate limiting and expiry on server side.

If you want, I can produce a small patch for the SmsReceiver (using Telephony.Sms.Intents.getMessagesFromIntent) and a JobIntentService replacement for HttpService as an example.


References and further reading (recommended):

Tuesday, February 2, 2016

Add WhatsApp‑style SMS OTP Verification to an Android App — Part I (auto-read OTP with BroadcastReceiver & Volley)

In my last articles i.e creating-rest-api-to-generate-otp-part-2 and creating-rest-api-to-generate-otp-part-1 you have learnt how to create the REST API to generate the OTP and get it verified through the website.

Now we will create an android app for which registration process is going to use this REST API to get the user registered.

In this guide I use the Volley library to make HTTP requests. We will discuss more about this Volley library in another article. Also, before going through this article you need to have basic knowledge about Android Services, BroadcastReceivers and IntentService:

This Part I covers project setup and the core helper classes. We will use a BroadcastReceiver to read the SMS whenever the device receives the OTP and an IntentService to execute the HTTP request that sends the received OTP back to the server for verification.

TL;DR

  • Build an Android app that requests an OTP from your REST API.
  • Your server should send an SMS containing a single, unique delimiter and the OTP (example: "SWNAND:1234").
  • App's BroadcastReceiver detects incoming SMS, extracts the OTP, and starts an IntentService to call the verification endpoint.
  • The app uses Volley for network calls and SharedPreferences (PrefManager) to store state.

Prerequisites

  • Android Studio (recommend recent stable version).
  • Minimum SDK: depends on your project; the article code assumes older support libs — consider migrating to AndroidX for modern projects.
  • Basic familiarity with Services, BroadcastReceiver, IntentService, and Gradle.

Permissions and Play Store considerations (important)

  • This tutorial reads SMS messages. On Android 6+ you must request runtime permissions (RECEIVESMS, READSMS) from the user.
  • Google Play has restrictions on apps requesting SMS permissions. For production apps consider using the SMS Retriever API (which doesn't require SMS read permissions) or carefully read Play Store policy and provide a strong justification for SMS permissions.
  • In this article we show the code and manifest entries used in the sample. If you publish your app to Play Store, confirm the current policy and consider alternatives.

Project setup (Android Studio)

  1. In Android Studio, create a new project via File ⇒ New Project and choose Blank Activity when prompted.

1

2

3

4

  1. Press Finish to create the project. This creates the Android project (SMSVerify).

3. Add Volley dependency

Open build.gradle (Module: app) and add the Volley dependency. The original article used 'com.mcxiaoke.volley:library-aar:1.0.0'. For modern projects, prefer the official artifact. Example:

// official Volley (example version)
implementation 'com.android.volley:volley:1.2.1'

// legacy: 'com.mcxiaoke.volley:library-aar:1.0.0' (older/unofficial)

(Choose the appropriate dependency for your project. If you remain on old support libraries, the legacy artifact may continue to work.)

5

4. Add string resources

Open res/values/strings.xml and add the following values:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">SMSVerify</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_sms">SMSVerify</string>
    <string name="action_logout">Logout</string>
    <string name="msg_enter_mobile">Enter your mobile number to get started!</string>
    <string name="lbl_name">Name</string>
    <string name="lbl_email">Email</string>
    <string name="lbl_mobile">Mobile</string>
    <string name="lbl_next">NEXT</string>
    <string name="msg_sit_back">Sit back &amp; Relax! while we verify your mobile number</string>
    <string name="msg_manual_otp">(Enter the OTP below in case if we fail to detect the SMS automatically)</string>
    <string name="lbl_enter_otp">Enter OTP</string>
    <string name="lbl_submit">SUBMIT</string>
</resources>

5. Add color resources

Open res/values/colors.xml and add:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#000000</color>
    <color name="bg_view_sms">#ffd423</color>
    <color name="bg_view_otp">#fc6d38</color>
</resources>

6. Styles (base and v21)

Open res/values/styles.xml and add:

<resources>
    <style name="MyMaterialTheme" parent="MyMaterialTheme.Base">
    </style>

    <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

Create res/values-v21/styles.xml and add (shared-element transition properties):

<resources>
    <style name="MyMaterialTheme" parent="MyMaterialTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>
</resources>

7. Set the app theme in AndroidManifest.xml

Open AndroidManifest.xml and set the theme on the tag:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="marutsoft.com.smsverify">

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher"
                 android:label="@string/app_name" android:supportsRtl="true"
                 android:theme="@style/MyMaterialTheme">
        ...
    </application>

</manifest>

8. Project packages

Create five packages to organize the project:

  • activity
  • app
  • helper
  • receiver
  • service

9. Config.java (app configuration)

Under the app package create Config.java. It contains app configuration and server endpoints.

/**
 * Created by Karjol G T on 01-02-2016.
 */

public class Config {

    // server URL configuration
    public static final String URL_REQUEST_SMS = "http://192.168.0.3/OTP_SMS/request_sms.php";
    public static final String URL_VERIFY_OTP =  "http://192.168.0.3/OTP_SMS/verify_otp.php";

    public static final String SMS_ORIGIN = "SWNAND";

    // special character to prefix the otp. Make sure this character appears only once in the sms
    public static final String OTP_DELIMITER = ":";
}

Note: replace the hard-coded 192.168.0.3 with your server hostname or an environment/config placeholder, for example:

public static final String URL_REQUEST_SMS = "http://<SERVER_IP>/OTP_SMS/request_sms.php";

10. MyApplication.java (Volley init)

Under the app package create MyApplication.java. This class initializes Volley core objects and provides a shared RequestQueue.

package marutsoft.com.smsverify.app;

import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

/**
 * Created by Karjol G T on 01-02-2016.
 */

public class MyApplication extends Application {
    public static final String TAG = MyApplication.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

Add MyApplication to AndroidManifest.xml by setting the application name if you want the class to be used automatically:

<application
    android:name="marutsoft.com.smsverify.app.MyApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/MyMaterialTheme">

    <!-- Activities, receivers, services go here -->

</application>

11. Custom ViewPager (disable swipe)

Under helper package create MyViewPager.java (a custom ViewPager that disables swipe):

package marutsoft.com.smsverify.helper;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Created by Karjol G T on 01-02-2016.
 */
public class MyViewPager extends ViewPager {

    public MyViewPager(Context context) {
        super(context);
    }

    public MyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }
}

If your project uses AndroidX, update imports to androidx.viewpager.widget.ViewPager.

12. PrefManager.java (SharedPreferences helper)

Under helper package create PrefManager.java. This class stores user information in SharedPreferences.

package marutsoft.com.smsverify.helper;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import java.util.HashMap;

/**
 * Created by Karjol G T on 01-02-2016.
 */

public class PrefManager {

    SharedPreferences pref;
    Editor editor;
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "AndroidHive";

    // All Shared Preferences Keys
    private static final String KEY_IS_WAITING_FOR_SMS = "IsWaitingForSms";
    private static final String KEY_MOBILE_NUMBER = "mobile_number";
    private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
    private static final String KEY_NAME = "name";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_MOBILE = "mobile";

    public PrefManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void setIsWaitingForSms(boolean isWaiting) {
        editor.putBoolean(KEY_IS_WAITING_FOR_SMS, isWaiting);
        editor.commit();
    }

    public boolean isWaitingForSms() {
        return pref.getBoolean(KEY_IS_WAITING_FOR_SMS, false);
    }

    public void setMobileNumber(String mobileNumber) {
        editor.putString(KEY_MOBILE_NUMBER, mobileNumber);
        editor.commit();
    }

    public String getMobileNumber() {
        return pref.getString(KEY_MOBILE_NUMBER, null);
    }

    public void createLogin(String name, String email, String mobile) {
        editor.putString(KEY_NAME, name);
        editor.putString(KEY_EMAIL, email);
        editor.putString(KEY_MOBILE, mobile);
        editor.putBoolean(KEY_IS_LOGGED_IN, true);
        editor.commit();
    }

    public boolean isLoggedIn() {
        return pref.getBoolean(KEY_IS_LOGGED_IN, false);
    }

    public void clearSession() {
        editor.clear();
        editor.commit();
    }

    public HashMap<String, String> getUserDetails() {
        HashMap<String, String> profile = new HashMap<>();
        profile.put("name", pref.getString(KEY_NAME, null));
        profile.put("email", pref.getString(KEY_EMAIL, null));
        profile.put("mobile", pref.getString(KEY_MOBILE, null));
        return profile;
    }
}

13. What’s next / Part II

The remaining part (reading SMS via BroadcastReceiver, starting the IntentService, HTTP verification flow, and UI wiring) will continue in Part II of this blog. In Part II I will include the receiver and service implementation and a demo of the complete verification flow.

Troubleshooting / Notes

  • If Gradle sync fails, verify your dependency versions and Android support vs AndroidX alignment.
  • If OTP is not detected, check SMS format on the server and confirm the delimiter and origin are present as configured in Config.java.
  • On Android 6+ ensure runtime permissions are requested and granted. If using the SMS Retriever API it avoids SMS read permissions.

The Remaining part, we will continue in next Part II of this blog.