In this tutorial, we will create firebase OTP authentication in android studio. We will pass data from previous activities which are signup OR forget password. In our previous tutorial we set up firebase in the android studio so, if you are new here then please watch this first.
Firebase OTP Setup
To start the firebase OTP authentication in the android studio we first have to set up the firebase authentication method by first adding the dependency in the project as defined the in here and then we have to Enable the phone number verification in Firebase Console.
Firebase OTP is not working
If your firebase otp is not working then please follow the instructions below. There are few new security policy related items added by Firebase after this tutorial uploaded. So, to use phone authentication we have to follow few new things.
- Change the sendVerificationCodeToUser() function as menthioned above by defining varible of mAuth and then initilize it.
- Open Build.Gradle (app level)
- Update all the dependencies in the app level build.Gradle file
- Update the compileSdkVersion to latest (31)
- Update the targetSdkVersion to latest (31)
- Update the buildToolsVersion to latest (30.0.2)
- Now Open Project level Build.Gradle file and update all dependencies in it.
- Open Manifest file and set android:exported=”true” in the main <activity> like
-
<activity android:name=".Common.SplashScreen"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
-
- Add SHA-256 in the Firebase Console
- Open firebase console and select project
- Goto Project Settings and scroll to the bottom to add Fingerprints SHA1 and SHA-256
- Now to get both fingerprints, open Android Studio
- Click on the Gradle from the right most tab
- Select your Project and right click on it to see a menu
- Select Refresh and you will see Tasks in your project
- Open Task -> Android -> and double click on signing report to generate SHA1 and SHA-256 certificates
- add them in firebase.
- Open firebase console and select project
- Download latest google-services.json file and add in your project
- Select project from the left android studio project menu
- Paste the file inside app directory
- Add Safety Net
- Goto Firebase console -> select app -> settings -> Select App check from the horizontal menu ->
- Select on the app and It will open a safety check -> select the agreement checkbox and click add
- Clean and rebuild project.
Get data from previous activities
As we call the OTP screen from previous screens so, we have to pass all the data or phone number from called activities like signup or forget a password to perform the phone authentication. So this is the code used to pass data from previous activities using Intent.
Complete phone Number
//Get complete phone number
String _getUserEnteredPhoneNumber = phoneNumber.getEditText().getText().toString().trim();
//Remove first zero if entered!
if (_getUserEnteredPhoneNumber.charAt(0) == '0') {
_getUserEnteredPhoneNumber = _getUserEnteredPhoneNumber.substring(1);
}
//Complete phone number
final String _phoneNo = "+" + countryCodePicker.getFullNumber() + _getUserEnteredPhoneNumber;
Pass Data From SignUp
Intent intent = new Intent(getApplicationContext(), VerifyOTP.class);
//Pass all fields to the next activity
intent.putExtra("fullName", _fullName);
intent.putExtra("email", _email);
intent.putExtra("username", _username);
intent.putExtra("password", _password);
intent.putExtra("date", _date);
intent.putExtra("gender", _gender);
intent.putExtra("phoneNo", _phoneNo);
intent.putExtra("whatToDO", "createNewUser"); // This is to identify that which action should OTP perform after verification.
//Add Transition
Pair[] pairs = new Pair[1];
pairs[0] = new Pair<View, String>(scrollView, "transition_OTP_screen");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(SignUp3rdClass.this, pairs);
startActivity(intent, options.toBundle());
} else {
startActivity(intent);
}
Receieve Data in OTP Screen
So we pass the data from previous screen and now we have to receieve it using Intent inside onCreate method.
Get Data
//Get all the data from Intent
fullName = getIntent().getStringExtra("fullName");
email = getIntent().getStringExtra("email");
username = getIntent().getStringExtra("username");
password = getIntent().getStringExtra("password");
date = getIntent().getStringExtra("date");
gender = getIntent().getStringExtra("gender");
phoneNo = getIntent().getStringExtra("phoneNo");
whatToDO = getIntent().getStringExtra("whatToDO");
Complete onCreate Method()
PinView pinFromUser;
String codeBySystem;
TextView otpDescriptionText;
String fullName, phoneNo, email, username, password, date, gender, whatToDO;
// [NEWLY Updated code -- START declare_mAuth]
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_verify_o_t_p);
//hooks
pinFromUser = findViewById(R.id.pin_view);
otpDescriptionText = findViewById(R.id.otp_description_text);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
//Get all the data from Intent
fullName = getIntent().getStringExtra("fullName");
email = getIntent().getStringExtra("email");
username = getIntent().getStringExtra("username");
password = getIntent().getStringExtra("password");
date = getIntent().getStringExtra("date");
gender = getIntent().getStringExtra("gender");
phoneNo = getIntent().getStringExtra("phoneNo");
whatToDO = getIntent().getStringExtra("whatToDO");
otpDescriptionText.setText("Enter One Time Password Sent Onn"+phoneNo);
sendVerificationCodeToUser(phoneNo);
}
Send Verification Code — [UPDATED]
This is the first function which will be called to send the phone number at user’s provided phone number!
Send Verification COde - LATEST
private void sendVerificationCodeToUser(String phoneNo) {
// [START start_phone_auth]
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(mAuth) //mAuth is defined on top
.setPhoneNumber(phoneNo) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
// [END start_phone_auth]
}
On Verification State change Callbacks
This is the 2nd function which will be called to check weather auto code send? manual code send or verification failed.
On Verification State Changed CallBacks
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks =
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
codeBySystem = s;
}
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
pinFromUser.setText(code);
verifyCode(code);
}
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Toast.makeText(VerifyOTP.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
};
Verify Code
This is the 3rd function which will be called to execute manual or auto methods and verifying the code send by the system and enter by the user.
On Verification State Changed CallBacks
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeBySystem, code);
signInWithPhoneAuthCredential(credential);
}
Sign In the user
This is the last function which will be called to weather show an error or perform the success message or action defined inside it.
SignIn With Phone Auth Credential
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//Verification completed successfully here Either
// store the data or do whatever desire
if (whatToDO.equals("updateData")) {
updateOldUsersData();
} else if (whatToDO.equals("createNewUser")) {
storeNewUsersData();
}
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(VerifyOTP.this, "Verification Not Completed! Try again.", Toast.LENGTH_SHORT).show();
}
}
}
});
}
Recommended Posts