RunCodes
Programming & Tech

How to Generate and Send OTP SMS for Free using Android?

2 9,602

As you all guyz know that security of user account is the critical problem in these days. So, the developer have to think about how they can secure their user account. This is can done by generating and sending OPT to the user phone number through SMS.

First understand what is OTP?

A One Time Password (OTP) is a unique code/token generated by our application, sent to a user via SMS text and then entered into our application login/signup flow for additional security.

  • People supply a mobile number when they join your service.
  • You generate a unique code and merge it into an SMS text and send to the user.
  • The user types the code into a form on your server and you verify the code matches.
  • You delete the code after a successful login or after a period of time.

One-Time Passwords are only effective for a fixed period of time and become invalid once the user logs in, making them exceptionally useful against spyware such as key logging programs.

One you have built One Time Passwords into your activation/signup flow a One Time Password will be texted every time a login attempt is made.  This flow will dramatically improve account security.

“This tutorial may be very useful for those who want to integrate OTP features in their project which is developed in Android”.

So for this, we have to take the help of SMS gateway to send the OTP to the user Phone Number.

We are going to take help of txtlocal as our SMS gateway. All you have do is go to http://www.txtlocal.co.uk and there you need to create one account. after creating account. (you need to fill up some of your information and txtlocal will send you a verification email into your email and verify your account [watch the video for detail]).After completing this step, go http://api.txtlocal.com/docs/sendsms and from the select language option choose java and then copy the code and edit as in the following manner or simply copy the following code but you need to provide your own api key when you run this project.

In this tutorial we are going to discuss about how we can insert, delete and update in SQLite Database using android programming in detail.

 

[sociallocker]

STEPS:

1. Before starting this tutorial, you need to have basic knowledge of android but if you are new to android programming it’s OK. it’s not a big deal you will learn gradually. So, in this first step, you need to have Android Studio installed in your system, i am using android studio of version 3.1.2. If you don’t have, download it from here: https://www.android.com/ and then set up AVD (Android Virtual Device). It may be either android studio built-in AVD or any other third party AVD like genymotion. One thing you need to take care while creating AVD is the AVD should be of api level below 22. This step complete the basic setup require to write our code and run it.

2. Open Android Studio, Click on file>new project. Give your application name whatever you want and then click next, select phone and tablet and then click next and then select empty activity and click next and then click on finish. It will take some time to build your gradle.

3. Goto app>res>layout>activity_main.xml by click the project field from left pane of your android studio and write the following code inside the ConstraintLayout tag. or Drag and Drop three plainText, three textview and two Button in your Layout. Now you have to change the properties of these controls (Copy the xml code from below). For more Detail, watch the video. In this step we complete the user interface part.


<?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=".MainActivity">

<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="Name"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/txtPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:hint="+977-0123-456-789"
android:inputType="textPersonName"
app:layout_constraintBaseline_toBaselineOf="@+id/textView3"
app:layout_constraintEnd_toEndOf="parent" />

<EditText
android:id="@+id/txtVerOTP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:hint="123456"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="@+id/btnVerOTP"
app:layout_constraintEnd_toEndOf="parent" />

<TextView
android:id="@+id/textView2"
android:layout_width="102dp"
android:layout_height="33dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Name"
android:textSize="25sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView3"
android:layout_width="111dp"
android:layout_height="40dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="98dp"
android:text="Phone"
android:textSize="25sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView4"
android:layout_width="110dp"
android:layout_height="40dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:text="verify otp"
android:textSize="25sp"
app:layout_constraintBaseline_toBaselineOf="@+id/txtVerOTP"
app:layout_constraintStart_toStartOf="parent" />

<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="20dp"
android:text="Login"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtPhone" />

<Button
android:id="@+id/btnVerOTP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="110dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:text="Verify OTP"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>

4. Now from the left top pane you may see app folder. Expand that folder and then go to java folder again expand top folder under java folder. Double click that MainActivity.java class and declare each control inside the class.

Button _btnLogin, _btnVerOTP;
EditText _txtName, _txtPhone, _txtVerOTP;
int randomNumber;

5. Inside the onCreate() method initialize the each controls as:

_txtName=(EditText)findViewById(R.id.txtName);
_txtPhone=(EditText)findViewById(R.id.txtPhone);
_txtVerOTP=(EditText)findViewById(R.id.txtVerOTP);
_btnLogin=(Button)findViewById(R.id.btnLogin);
_btnVerOTP=(Button)findViewById(R.id.btnVerOTP);

6. Now create listening event of the button and write the following piece of code.


_btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
// Construct data
String apiKey = "apikey=" + "YOUR_API_KEY";
Random random= new Random();
randomNumber=random.nextInt(999999);
String message = "&message=" + "Hey "+_txtName.getText().toString()+ "Your OTP IS "+randomNumber;
String sender = "&sender=" + "TSN";
String numbers = "&numbers=" +_txtPhone.getText().toString();

// Send data
HttpURLConnection conn = (HttpURLConnection) new URL("https://api.txtlocal.com/send/?").openConnection();
String data = apiKey + numbers + message + sender;
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length", Integer.toString(data.length()));
conn.getOutputStream().write(data.getBytes("UTF-8"));
final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
stringBuffer.append(line);
}
rd.close();
Toast.makeText(getApplicationContext(), "OTP SEND SUCCESSFULLY", Toast.LENGTH_LONG).show();

//return stringBuffer.toString();
} catch (Exception e) {
//System.out.println("Error SMS "+e);
///return "Error "+e;
Toast.makeText(getApplicationContext(), "ERROR SMS "+e, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "ERROR "+e, Toast.LENGTH_LONG).show();
}
}
});

7. Now what we need to do is, we need to check whether the user enter the exact same OTP or enter any number haphazardly. So write the below code where clicking event of login button finished.


_btnVerOTP.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(randomNumber==Integer.valueOf(_txtVerOTP.getText().toString())){
Toast.makeText(getApplicationContext(), "You are logined successfully", Toast.LENGTH_LONG).show();

}else{
Toast.makeText(getApplicationContext(), "WRONG OTP", Toast.LENGTH_LONG).show();
}

}
});

8. We are sending OTP from online so we need to give permission to your app to use internet. So, goto your manifest.xml file and add the following permission before the application tag but below the manifest tag.

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

9. After completing above step, if you run your project either in any emulator or Android Studio builtin ADB, you will see the os.NetworkOnMainThreadException because You should almost always run network operations on a thread or as an asynchronous task. So, Create the thread and write the above code inside that thread or strict the thread and write the following code inside the onCreate method just below your initialized controls.

StrictMode.ThreadPolicy policy= new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

10. Now Login to the your txtlocal account, goto setting>API KEY and then click on create API Key and then simply copy that created key.That’s it guyz. Now RUN Your apps in any AVD and Enter your Name, Phone number with country code in the respective textbox and then click on Login button. And when you receive OTP enter that OTP in OTP textbox. That’s it.

May be after sending 10 OTP SMS your credit will be finished! but don’t be sad you can send more and more OTP SMS but you need to create another account with another email account in www.txtlocal.co.uk ! that’s it. you may not be that much happy to hear this (sending only 10 OTP SMS) but don’t forget you are able to send these 10 OTP SMS for free and also there is one line “To get something, you must lose something”. it means you have to spend some time in creating account in txtlocal.co.uk in order to send free OTP SMS.

Finally, if you guyz think, this is awesome tutorial and help you in some extend please share this tutorials with your all friend so that they can know about this method of sending OTP SMS!

[/sociallocker]

 

if you have any confusion, you can watch the following video:

 

Show Comments (2)