Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

android - OTP (token) should be automatically read from the message

I am working on an Android App, in which the server sends an OTP and the user needs to enter this OTP in the App, to SignUp for my App. What I want is, that my App should be able to automatically read the OTP sent by the server. How can I achieve this? Any help or guidance in this regard would be highly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I will recommend you not to use any third party libraries for auto fetch OTP from SMS Inbox. This can be done easily if you have basic understanding of Broadcast Receiver and how it works. Just Try following approach :

  1. Create single interface i.e SmsListner
package com.wnrcorp.reba;
public interface SmsListener {
    public void messageReceived(String messageText);
}
  1. Create single Broadcast Receiver i.e SmsReceiver
package com.wnrcorp.reba;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver {
    private static SmsListener mListener;
    Boolean b;
    String abcd, xyz;
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle data = intent.getExtras();
        Object[] pdus = (Object[]) data.get("pdus");
        for (int i = 0; i < pdus.length; i++) {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
            String sender = smsMessage.getDisplayOriginatingAddress();
            // b=sender.endsWith("WNRCRP");  //Just to fetch otp sent from WNRCRP
            String messageBody = smsMessage.getMessageBody();
            abcd = messageBody.replaceAll("[^0-9]", ""); // here abcd contains otp 
            which is in number format
            //Pass on the text to our listener.
            if (b == true) {
                mListener.messageReceived(abcd); // attach value to interface 
                object
            } else {}
        }
    }
    public static void bindListener(SmsListener listener) {
        mListener = listener;
    }
}
  1. Add Listener i.e broadcast receiver in android manifest file
<receiver android:name=".SmsReceiver">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    </intent-filter>
</receiver>

and add permission

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
  1. The activity where you going to auto fetch otp when it is received in inbox. In my case I'm fetching otp and setting on edittext field.
public class OtpVerificationActivity extends AppCompatActivity {
    EditText ed;
    TextView tv;
    String otp_generated, contactNo, id1;
    GlobalData gd = new GlobalData();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_otp_verification);
            ed = (EditText) findViewById(R.id.otp);
            tv = (TextView) findViewById(R.id.verify_otp);
            /*This is important because this will be called every time you receive 
             any sms */
            SmsReceiver.bindListener(new SmsListener() {
                @Override
                public void messageReceived(String messageText) {
                    ed.setText(messageText);
                }
            });
            tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            InputMethodManager imm =
                                (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                        } catch (Exception e) {}
                        if (ed.getText().toString().equals(otp_generated)) {
                            Toast.makeText(OtpVerificationActivity.this, "OTP Verified 
                                Successfully!", Toast.LENGTH_SHORT).show();           
                            }
                        });
                }
            }
}

Layout File for OtpVerificationActivity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_otp_verification"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.wnrcorp.reba.OtpVerificationActivity">
    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/firstcard"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        card_view:cardCornerRadius="10dp"
        >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="@android:color/white">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="OTP Confirmation"
                android:textSize="18sp"
                android:textStyle="bold"
                android:id="@+id/dialogTitle"
                android:layout_margin="5dp"
                android:layout_gravity="center"
                />
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/otp"
                android:layout_margin="5dp"
                android:hint="OTP Here"
                />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Verify"
                android:textSize="18sp"
                android:id="@+id/verify_otp"
                android:gravity="center"
                android:padding="10dp"
                android:layout_gravity="center"
                android:visibility="visible"
                android:layout_margin="5dp"
                android:background="@color/colorPrimary"
                android:textColor="#ffffff"
                />
        </LinearLayout>
    </android.support.v7.widget.CardView>
</RelativeLayout>

Screenshots for OTP Verification Activity where you fetch OTP as soons as messages received enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...