How To Get OTP(One-Time-Password) from Register Mobile Number

 Today we will explain the  Firebase Mobile Verification code. It provides various features that we need for the backend of your application.You enter your phone/mobile number, receives an OTP, and then you use that OTP to authenticate.i will give you code to download and more efficient screen design and follow me.

Lets follow the steps,you need to develope this code add dependence first

dependencies {
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:support-vector-drawable:25.3.1'
    compile 'com.google.firebase:firebase-auth:11.0.1'
    compile 'com.google.firebase:firebase-database:11.0.1'
    compile 'com.google.firebase:firebase-storage:11.0.1'
    compile 'com.android.support:design:25.3.1'
}
apply plugin: 'com.google.gms.google-services'

After Completed this go to src folder create PhoneLogin.java class with activity screen.Here,
i write code in this class as below:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.icu.util.TimeUnit;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.e_recharge.au.ToastViews.MyCustomToast;
import com.e_recharge.au.ToastViews.MyDynamicToast;
import com.e_recharge.au.brodcasts.IncomingSms;
import com.e_recharge.au.fonts.AppPreferences;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;

public class PhoneLogin extends AppCompatActivity {
    private static final String TAG = "PhoneLogin";
    private boolean mVerificationInProgress = false;
    private String mVerificationId;
    private PhoneAuthProvider.ForceResendingToken mResendToken;
    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
    private FirebaseAuth mAuth;
    TextView t1, t2, otp_bigtxt;
    EditText e1, e2, user_name;
    Button b1, b2;

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

        e1 = (EditText) findViewById(R.id.Phonenoedittext);
        b1 = (Button) findViewById(R.id.PhoneVerify);
        t1 = (TextView) findViewById(R.id.text_mb_val);
        otp_bigtxt = (TextView) findViewById(R.id.otp_bigtxt);
        e2 = (EditText) findViewById(R.id.OTPeditText);
        user_name = (EditText) findViewById(R.id.user_name);
        b2 = (Button) findViewById(R.id.OTPVERIFY);
        t2 = (TextView) findViewById(R.id.otpvalue);
        mAuth = FirebaseAuth.getInstance();
        mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

            @Override
            public void onVerificationCompleted(PhoneAuthCredential credential) {
                mVerificationInProgress = false;
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {
                MyDynamicToast.errorMessage(PhoneLogin.this, "Verification Failed");
                if (e instanceof FirebaseAuthInvalidCredentialsException) {
                    MyDynamicToast.warningMessage(PhoneLogin.this, "InValid Phone Number");
                    // ...
                } else if (e instanceof FirebaseTooManyRequestsException) {
                }

            }

            @Override
            public void onCodeSent(String verificationId,
                                   PhoneAuthProvider.ForceResendingToken token) {
                // Log.d(TAG, "onCodeSent:" + verificationId);
                MyDynamicToast.successMessage(PhoneLogin.this, "Verification code has been send on your number");
                mVerificationId = verificationId;
                mResendToken = token;
                e1.setVisibility(View.GONE);
                user_name.setVisibility(View.GONE);
                b1.setVisibility(View.GONE);
                t1.setVisibility(View.GONE);
                t2.setVisibility(View.VISIBLE);
                e2.setVisibility(View.VISIBLE);
                b2.setVisibility(View.VISIBLE);
                otp_bigtxt.setVisibility(View.VISIBLE);
            }
        };

        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String uname = user_name.getText().toString().trim();

                if (uname.length() == 0) {
                    MyDynamicToast.errorMessage(getApplicationContext(), getString(R.string.namefull));
                    return;
                }
                if (uname.length()<3||uname.length()>10){
                    MyDynamicToast.errorMessage(getApplicationContext(), "Your Nick Name must 10 letters only");
                    return;
                }

                String mobileno = e1.getText().toString();
                if (mobileno.length() == 0) {
                    MyDynamicToast.errorMessage(getApplicationContext(), getString(R.string.entno));
                    return;
                }
                if (mobileno.length() < 10) {
                    MyDynamicToast.warningMessage(getApplicationContext(), getString(R.string.entervno));
                    return;
                }
                PhoneAuthProvider.getInstance().verifyPhoneNumber(
                        mobileno,
                        60,
                        java.util.concurrent.TimeUnit.SECONDS,
                        PhoneLogin.this,
                        mCallbacks);
            }
        });

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String opt = e2.getText().toString();
                if (opt.length() == 0) {
                    MyDynamicToast.errorMessage(getApplicationContext(), getString(R.string.entotp));
                    return;
                }
                PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, opt);
                signInWithPhoneAuthCredential(credential);
            }
        });
    }
    private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            startActivity(new Intent(PhoneLogin.this, ErecharePage.class));
                            AppPreferences.getInstance(getApplicationContext()).addToStore("mobileno", e1.getText().toString());
                            AppPreferences.getInstance(getApplicationContext()).addToStore("username", user_name.getText().toString().toString());
                            MyDynamicToast.successMessage(PhoneLogin.this, "Verification Done");
                            finish();
                        } else {
                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                MyDynamicToast.errorMessage(PhoneLogin.this, "Invalid Verification");
                            }
                        }
                    }
                });
    }

    @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);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase("otp")) {
                final String message = intent.getStringExtra("message");
                otp_bigtxt.setText(Html.fromHtml("<h4>Your Received otp: </h4>" + message));
                e2.setText(message);
                PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, message);
                signInWithPhoneAuthCredential(credential);
            }
        }
    };

}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:customtv="http://schemas.android.com/apk/res-auto"
    android:background="@mipmap/background_chimg"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="50dp"
        android:layout_marginLeft="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginTop="50dp"
        android:background="@color/white">

        <RelativeLayout
            android:id="@+id/mobile_screen"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">


            <com.e_recharge.au.fonts.CustomTextView
                android:id="@+id/text_mb_val"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="5dp"
                android:gravity="center"
                android:padding="5dp"
                android:text="@string/register"
                android:textColor="@color/bs_blue"
                android:textSize="16dp" />

            <EditText
                android:id="@+id/user_name"
                style="@style/Base.Widget.AppCompat.EditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/text_mb_val"
                android:layout_margin="10dp"
                android:hint="@string/name"
                android:inputType="textCapSentences"
                android:maxLength="10"
                android:padding="10dp"
                android:paddingLeft="5dp"
                android:paddingRight="5dp"
                android:singleLine="true" />

            <EditText
                android:id="@+id/Phonenoedittext"
                style="@style/Base.Widget.AppCompat.EditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/user_name"
                android:layout_margin="10dp"
                android:hint="@string/mobile"
                android:inputType="number"
                android:maxLength="10"
                android:padding="10dp"
                android:paddingLeft="5dp"
                android:paddingRight="5dp"
                android:singleLine="true" />

            <Button
                android:id="@+id/PhoneVerify"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignEnd="@+id/Phonenoedittext"
                android:layout_alignLeft="@+id/Phonenoedittext"
                android:layout_alignRight="@+id/Phonenoedittext"
                android:layout_alignStart="@+id/Phonenoedittext"
                android:layout_below="@+id/Phonenoedittext"
                android:background="@drawable/cmts_bg"
                android:text="Send OTP" />

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/mobile_screen">

            <com.e_recharge.au.fonts.CustomTextView
                android:id="@+id/otpvalue"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="5dp"
                android:gravity="center"
                android:padding="5dp"
                android:text="@string/otp"
                android:textColor="@color/bs_blue"
                android:textSize="16dp"
                android:visibility="gone" />

            <EditText
                android:id="@+id/OTPeditText"
                style="@style/Base.Widget.AppCompat.EditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/otpvalue"
                android:layout_margin="10dp"
                android:hint="@string/otpno"
                android:maxLength="6"
                android:padding="10dp"
                android:paddingLeft="5dp"
                android:paddingRight="5dp"
                android:singleLine="true"
                android:visibility="gone" />

            <Button
                android:id="@+id/OTPVERIFY"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignEnd="@+id/OTPeditText"
                android:layout_alignLeft="@+id/OTPeditText"
                android:layout_alignRight="@+id/OTPeditText"
                android:layout_alignStart="@+id/OTPeditText"
                android:layout_below="@+id/OTPeditText"
                android:background="@drawable/layout_back"
                android:text="Verify"
                android:visibility="gone" />

            <com.e_recharge.au.fonts.CustomTextView
                android:id="@+id/otp_bigtxt"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="5dp"
                android:gravity="center"
                android:padding="5dp"
                android:textColor="@color/bs_blue"
                android:textSize="20dp"
                android:layout_below="@+id/OTPVERIFY"
                android:visibility="gone"
                customtv:fontType="5"/>
        </RelativeLayout>
    </RelativeLayout>
</LinearLayout>


Comments