在我的应用程序中,我正在使用google-api(通过Gmail验证用户),FireBase(用于发送otp)。验证用户后,我想通过Http服务将所有值(姓名,电子邮件,个人资料和手机号码)发布到我的数据库中,下面是代码。
// [START initialize_auth]
mAuth = FirebaseAuth.getInstance();
// [END initialize_auth]
// Initialize phone auth callbacks
// [START phone_auth_callbacks]
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
// 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 verification without
// user action.
Log.d(TAG1, "onVerificationCompleted:" + credential);
// [START_EXCLUDE silent]
mVerificationInProgress = false;
// [END_EXCLUDE]
// [START_EXCLUDE silent]
// Update the UI and attempt sign in with the phone credential
updateUI(STATE_VERIFY_SUCCESS, credential);
// [END_EXCLUDE]
signInWithPhoneAuthCredential(credential);
}
@Override
public void onVerificationFailed(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(TAG1, "onVerificationFailed", e);
// [START_EXCLUDE silent]
mVerificationInProgress = false;
// [END_EXCLUDE]
if (e instanceof FirebaseAuthInvalidCredentialsException) {
// Invalid request
// [START_EXCLUDE]
mPhoneNumberField.setError("Invalid phone number.");
// [END_EXCLUDE]
} else if (e instanceof FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
// [START_EXCLUDE]
Snackbar.make(findViewById(android.R.id.content), "Quota exceeded.",
Snackbar.LENGTH_SHORT).show();
// [END_EXCLUDE]
}
// Show a message and update the UI
// [START_EXCLUDE]
updateUI(STATE_VERIFY_FAILED);
// [END_EXCLUDE]
}
@Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
// 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.
Log.d(TAG1, "onCodeSent:" + verificationId);
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
// [START_EXCLUDE]
// Update UI
updateUI(STATE_CODE_SENT);
// [END_EXCLUDE]
}
};
// [END phone_auth_callbacks]
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
Log.e(TAG, "display name: " + acct.getDisplayName());
personName = acct.getDisplayName();
email = acct.getEmail();
Log.e(TAG, "Name: " + personName + ", email: " + email
);
txtName.setText(personName);
txtEmail.setText(email);
try {
personPhotoUrl = acct.getPhotoUrl().toString();
Glide.with(getApplicationContext()).load(personPhotoUrl)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgProfilePic);
} catch (Exception e) {
imgProfilePic.setImageResource(R.mipmap.user1);
}
updateUI(true);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_sign_in:
signIn();
break;
case R.id.button_start_verification:
if (!validatePhoneNumber()) {
return;
}
///////hide keyboard start
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
startPhoneNumberVerification(mPhoneNumberField.getText().toString());
break;
case R.id.button_verify_phone:
String code = mVerificationField.getText().toString();
if (TextUtils.isEmpty(code)) {
mVerificationField.setError("Cannot be empty.");
return;
}
verifyPhoneNumberWithCode(mVerificationId, code);
break;
case R.id.button_resend:
resendVerificationCode(mPhoneNumberField.getText().toString(), mResendToken);
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
// [START_EXCLUDE]
if (mVerificationInProgress && validatePhoneNumber()) {
startPhoneNumberVerification(mPhoneNumberField.getText().toString());
}
// [END_EXCLUDE]
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
showProgressDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
private void updateUI(FirebaseUser currentUser) {
}
private void updateUI(int uiState, FirebaseUser user) {
updateUI(uiState, user, null);
}
private void updateUI(int uiState, PhoneAuthCredential cred) {
updateUI(uiState, null, cred);
}
private void updateUI(int uiState, FirebaseUser user, PhoneAuthCredential cred) {
switch (uiState) {
case STATE_INITIALIZED:
// Initialized state, show only the phone number field and start button
mStartButton.setVisibility(View.VISIBLE);
mPhoneNumberField.setVisibility(View.VISIBLE);
mVerifyButton.setVisibility(View.GONE);
mResendButton.setVisibility(View.GONE);
break;
case STATE_CODE_SENT:
// Code sent state, show the verification field, the
mVerifyButton.setVisibility(View.VISIBLE);
mResendButton.setVisibility(View.VISIBLE);
mVerificationField.setVisibility(View.VISIBLE);
mStartButton.setVisibility(View.GONE);
Toast.makeText(LoginActivity.this, "OTP Sent to Your mobile number",
Toast.LENGTH_LONG).show();
break;
case STATE_VERIFY_FAILED:
// Verification has failed, show all options
mStartButton.setVisibility(View.VISIBLE);
mVerifyButton.setVisibility(View.VISIBLE);
mResendButton.setVisibility(View.VISIBLE);
mPhoneNumberField.setVisibility(View.VISIBLE);
mVerificationField.setVisibility(View.VISIBLE);
Toast.makeText(LoginActivity.this, "Verification Failed",
Toast.LENGTH_LONG).show();
break;
case STATE_VERIFY_SUCCESS:
// Verification has succeeded, proceed to firebase sign in
mStartButton.setVisibility(View.GONE);
mVerifyButton.setVisibility(View.GONE);
mResendButton.setVisibility(View.GONE);
mPhoneNumberField.setVisibility(View.GONE);
mVerificationField.setVisibility(View.GONE);
Toast.makeText(LoginActivity.this, "Verification SuccessFull",
Toast.LENGTH_LONG).show();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://49.207.9.254/leonas/register.php?name="+ personName +"&email="+ email +"&picture="+ personPhotoUrl +"&phone="+ phonenum);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
JSONObject jsonObj = new JSONObject();
jsonObj.put("Result", jsonarray);
String msg = jsonObj.getJSONArray("Result").getJSONObject(1).getString("message");
String successmsg = "account successfully created.";
if (msg.equalsIgnoreCase(successmsg)) {
Toast.makeText(getApplicationContext(), "Your Account created Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Something went wrong...", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
Toast.makeText(getApplicationContext(), "Network Failed", Toast.LENGTH_SHORT).show();
}
// Set the verification text based on the credential
if (cred != null) {
if (cred.getSmsCode() != null) {
mVerificationField.setText(cred.getSmsCode());
} else {
mVerificationField.setText("");
mVerificationField.setTextColor(Color.parseColor("#4bacb8"));
}
}
break;
case STATE_SIGNIN_FAILED:
// No-op, handled by sign-in check
Toast.makeText(LoginActivity.this, "Verification Failed",
Toast.LENGTH_LONG).show();
break;
case STATE_SIGNIN_SUCCESS:
break;
}
}
我能够获得Gmail帐户和OTP验证也很完美但经过验证成功的消息我的http服务无法正常工作。帮助我解决这个问题。 下面是logcat:
03-21 11:55:54.543 1150-1661/? E/AudioMixer: AudioMixer::getTrackName out of available tracks
03-21 11:55:54.543 1150-1661/? E/AudioFlinger: no more track names available
03-21 11:55:54.543 1150-1661/? E/AudioFlinger: createTrack_l() initCheck failed -12; no control block?
03-21 11:55:54.544 1556-1659/system_process E/AudioTrack: AudioFlinger could not create track, status: -12
03-21 11:55:54.566 1556-1659/system_process E/SoundPool: Error creating AudioTrack
03-21 11:55:54.940 20822-20822/com.google.android.gms.ui E/libprocessgroup: failed to make and chown /acct/uid_10007: Read-only file system
03-21 11:56:13.455 1150-1661/? E/AudioMixer: AudioMixer::getTrackName out of available tracks
03-21 11:56:13.455 1150-1661/? E/AudioFlinger: no more track names available
03-21 11:56:13.455 1150-1661/? E/AudioFlinger: createTrack_l() initCheck failed -12; no control block?
03-21 11:56:13.455 1556-1659/system_process E/AudioTrack: AudioFlinger could not create track, status: -12
03-21 11:56:13.484 1556-1659/system_process E/SoundPool: Error creating AudioTrack
03-21 11:56:16.274 19620-19620/com.example.lenovo.invitationapp E/LoginActivity: display name: Sathish Manikanta
03-21 11:56:16.274 19620-19620/com.example.lenovo.invitationapp E/LoginActivity: Name: Sathish Manikanta, email: sathishmanikanta426@gmail.com
03-21 11:56:18.857 2013-2013/com.google.android.gms.persistent E/BluetoothAdapter: Bluetooth binder is null
03-21 11:57:25.710 1150-1150/? E/AudioMixer: AudioMixer::getTrackName out of available tracks
03-21 11:57:25.710 1150-1150/? E/AudioFlinger: no more track names available
03-21 11:57:25.710 1150-1150/? E/AudioFlinger: createTrack_l() initCheck failed -12; no control block?
03-21 11:57:25.710 1556-1659/system_process E/AudioTrack: AudioFlinger could not create track, status: -12
03-21 11:57:25.711 1556-1659/system_process E/SoundPool: Error creating AudioTrack
03-21 11:57:28.666 1150-1150/? E/AudioMixer: AudioMixer::getTrackName out of available tracks
03-21 11:57:28.666 1150-1150/? E/AudioFlinger: no more track names available
03-21 11:57:28.666 1150-1150/? E/AudioFlinger: createTrack_l() initCheck failed -12; no control block?
03-21 11:57:28.666 1556-1659/system_process E/AudioTrack: AudioFlinger could not create track, status: -12
03-21 11:57:28.667 1556-1659/system_process E/SoundPool: Error creating AudioTrack