-
Notifications
You must be signed in to change notification settings - Fork 0
/
MobileAuthActivity.java
285 lines (237 loc) · 11.5 KB
/
MobileAuthActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package com.example.firebaseauthexample.activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.firebaseauthexample.R;
import com.example.firebaseauthexample.customview.OTPView.OTPListener;
import com.example.firebaseauthexample.customview.OTPView.OtpTextView;
import com.example.firebaseauthexample.utils.MyUtils;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.credentials.Credential;
import com.google.android.gms.auth.api.credentials.HintRequest;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
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;
import java.util.concurrent.TimeUnit;
public class MobileAuthActivity extends AppCompatActivity {
public static final int PHONE_HINT = 100;
public static final String TAG = MobileAuthActivity.class.getName();
AppCompatActivity mActivity;
Context context;
TextInputEditText tiet_mobile_number;
LinearLayout ll_phone_number_input_view, ll_otp_verification_view;
Button btn_send_verification;
OtpTextView otp_view;
TextView tv_resend_otp;
boolean isOTPViewVisible = false;
FirebaseAuth mAuth;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mobile_auth_activity);
mActivity = this;
context = getApplicationContext();
initComponent();
try {
contactHint();
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
btn_send_verification.setOnClickListener(v -> {
if (!validatePhoneNumber()) {
return;
}
String finalPhoneNumber;
String phoneNumber = tiet_mobile_number.getText().toString();
if (phoneNumber.contains("+91")) {
finalPhoneNumber = phoneNumber.replace("+91", "");
} else {
finalPhoneNumber = phoneNumber;
}
callBackMethod();
startPhoneNumberVerification("+91" + finalPhoneNumber);
});
otp_view.setOtpListener(new OTPListener() {
@Override
public void onInteractionListener() {
}
@Override
public void onOTPComplete(String otp) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, otp);
signInWithPhoneAuthCredential(credential);
}
});
tv_resend_otp.setOnClickListener(view -> {
String finalPhoneNumber;
String phoneNumber = tiet_mobile_number.getText().toString();
if (phoneNumber.contains("+91")) {
finalPhoneNumber = phoneNumber.replace("+91", "");
} else {
finalPhoneNumber = phoneNumber;
}
resendVerificationCode("+91" + finalPhoneNumber, mResendToken);
MyUtils.showToast(mActivity,"OTP sent to given no. once again!");
});
}
private void initComponent() {
tiet_mobile_number = findViewById(R.id.tiet_mobile_number);
ll_phone_number_input_view = findViewById(R.id.ll_phone_number_input_view);
ll_otp_verification_view = findViewById(R.id.ll_otp_verification_view);
btn_send_verification = findViewById(R.id.btn_send_verification);
otp_view = findViewById(R.id.otp_view);
tv_resend_otp = findViewById(R.id.tv_resend_otp);
}
private void contactHint() throws IntentSender.SendIntentException {
GoogleApiClient apiClient = new GoogleApiClient.Builder(context)
.addApi(Auth.CREDENTIALS_API)
.build();
HintRequest hintRequest = new HintRequest.Builder()
.setPhoneNumberIdentifierSupported(true)
.build();
PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(
apiClient, hintRequest);
startIntentSenderForResult(intent.getIntentSender(),
PHONE_HINT, null, 0, 0, 0);
}
private boolean validatePhoneNumber() {
String phoneNumber = tiet_mobile_number.getText().toString();
if (TextUtils.isEmpty(phoneNumber)) {
tiet_mobile_number.setError("Invalid phone number");
return false;
} else if (TextUtils.isEmpty(tiet_mobile_number.getText()) || (tiet_mobile_number.getText().length() != 10 && tiet_mobile_number.getText().length() != 13)) {
tiet_mobile_number.setError("Number should be 10 or 13 digits only");
return false;
}
return true;
}
private void startPhoneNumberVerification(String phoneNumber) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
mActivity, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
private void resendVerificationCode(String phoneNumber,
PhoneAuthProvider.ForceResendingToken token) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks, // OnVerificationStateChangedCallbacks
token); // ForceResendingToken from callbacks
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
MyUtils.showToast(mActivity, "Signin Successfully", Toast.LENGTH_LONG);
} else {
// Sign in failed, display a message and update the UI
Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
MyUtils.showToast(mActivity, "Invalid code.", Toast.LENGTH_LONG);
}
}
}
});
}
private void callBackMethod() {
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
// This callback will be invoked in two situations:
// 1 - Instant verification. In some cases the phone number can be instantly
// verified without needing to send or enter a verification code.
// 2 - Auto-retrieval. On some devices Google Play services can automatically
// detect the incoming verification SMS and perform verificaiton without
// user action.
Log.w(TAG, "onVerificationCompleted:" + phoneAuthCredential);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
// This callback is invoked in an invalid request for verification is made,
// for instance if the the phone number format is not valid.
Log.w(TAG, "onVerificationFailed", e);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
tiet_mobile_number.setError("Invalid phone number.");
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(mActivity, "Quota is exceeded, Please contact to admin", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(verificationId, forceResendingToken);
// The SMS verification code has been sent to the provided phone number, we
// now need to ask the user to enter the code and then construct a credential
// by combining the code with a verification ID.
ll_phone_number_input_view.setVisibility(View.GONE);
ll_otp_verification_view.setVisibility(View.VISIBLE);
isOTPViewVisible = true;
otp_view.requestFocusOTP();
Log.d(TAG, "onCodeSent:" + verificationId);
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = forceResendingToken;
}
};
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHONE_HINT) {
if (resultCode == RESULT_OK) {
Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
String phoneNumber = null;
if (credential.getId().contains("+91")) {
phoneNumber = credential.getId().replace("+91", "");
} else {
phoneNumber = credential.getId();
}
tiet_mobile_number.setText(phoneNumber);
}
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (isOTPViewVisible) {
finish();
Intent intent = new Intent(mActivity,MobileAuthActivity.class);
startActivity(intent);
} else {
finish();
}
}
}