Question Detail

How to read OTP Message for auto deduct OTP and fill in Edittext from Messanger?

4 years ago Views 1271 Visit Post Reply

I am Working on an Android App and Using OTP Verification. I have no idea how to read OTP Automatically from Messagebox?
I have searched on google but not get the desired answer. Is there any Testing Free SMS API Available?


Thread Reply

Anonymous

- 3 years ago

You need to use Broadcast Receiver to perform it.

you can download Source Code Here

 

Add this code to your Manifest.XML

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

 

<receiver android:name=".receivers.OTPBroadCastReceiver">
    <intent-filter android:priority="999">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

Create MainActivity.java

 

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    TextView otpOnlyTextView, fullmessageTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        otpOnlyTextView = (TextView) findViewById(R.id.opt_textView_ID);
        fullmessageTextView = (TextView) findViewById(R.id.fullmessage_textView_ID);
        Button sendMsg=(Button)findViewById(R.id.sendMsg_ID);
        sendMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //sendMessageAPILINK(); USE ANY API TO SEND MESSAGE OR SEND ANY NORMAL MESSAGE THROUGH YOUR ANOTHER NUMBER
                checkAndRequestPermissions();
            }
        });
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase("otp")) {
                final String message = intent.getStringExtra("message");
                final String sender = intent.getStringExtra("Sender");
                otpOnlyTextView.setText(message.replaceAll("\\D+", ""));
                fullmessageTextView.setText(sender + " : " + message);
                Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
                Log.e("OTP MESSSGE", message);
            }
        }
    };

    private boolean checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(android.Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            int receiveSMS = ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECEIVE_SMS);
            int readSMS = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_SMS);
            List<String> listPermissionsNeeded = new ArrayList<>();
            if (receiveSMS != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.RECEIVE_SMS);
            }
            if (readSMS != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(android.Manifest.permission.READ_SMS);
            }
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this,
                        listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 1);
                return false;
            }
            return true;
        }
        return true;

    }

    @Override
    public void onResume() {
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

}

 

create  receivers.OTPBroadCastReceiver.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.SmsMessage;


public class OTPBroadCastReceiver extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent)
    {
        // Get Bundle object contained in the SMS intent passed in
        Bundle bundle = intent.getExtras();
        SmsMessage[] smsMsg = null;
        String smsStr ="";
        if (bundle != null)
        {
            // Get the SMS message
            Object[] pdus = (Object[]) bundle.get("pdus");
            smsMsg = new SmsMessage[pdus.length];
            for (int i=0; i<smsMsg.length; i++){
                smsMsg[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                smsStr = smsMsg[i].getMessageBody().toString();

                String Sender = smsMsg[i].getOriginatingAddress();
                //Check here sender is yours
                Intent smsIntent = new Intent("otp");
                smsIntent.putExtra("message",smsStr);
                smsIntent.putExtra("Sender",Sender);
                LocalBroadcastManager.getInstance(context).sendBroadcast(smsIntent);
            }
        }
    }
}

Hemant Sharma

- 4 months ago

To auto read OTP in android using SMS Retriever API. You have to set up your message according to the google development guide, Here I am sharing how to get an Application hash code

  • SMS should start with <#> tag,
  • SMS should end with application hash code, etc.

 

  1. Go To Play store Console > App > Release > Setup > App Integrity (Play App Signing)
  2. Download App signing key certificate from the top right button
  3. This will give you deployment_cert.der file
  4. you need to Convert the deployment_cert.der file to a .jks file by use below command
  5. Open CMD or any terminal and replace YOUR_ALIAS file path and YOUR PASSWORD with yours which used in Keystore
keytool -importcert -alias YOUR_ALIAS -file D:\Project\KEYDATA\deployment_cert.der -keystore D:\Project\Folder\certificate.jks -storepass YOUR_PASSWORD

After entering this command it will ask

Trust this certificate? [no]: yes

type yes and click enter . It will show message

Certificate was added to keystore

This will generate a new file certificate.jks

 

  1. Now in terminal enter command

    keytool -exportcert -alias YOUR_ALIAS -keystore certificate.jks | xxd -p | tr -d "[:space:]" | echo -n YOUR_PACKAGE `cat` | sha256sum | tr -d "[:space:]-" | xxd -r -p | base64 | cut -c1-11

Replace YOUR_ALIAS,YOUR_PACKAGE with yours which used in keystore,project . In place of certificate.jks use complete path if required

it will ask for password

Enter keystore password: mypassword

enter your password and you will get the hash.