Firebase的电话身份验证在Android Studio上不起作用

时间:2020-04-11 20:01:04

标签: java firebase firebase-authentication

电话验证不起作用。我找不到任何错误。但是屏幕上似乎出现了onVerificationFailed方法吐司消息(“ Verification Failed enter image description here”)。救救我吧!...

活动主xml ------------------------------------------- < / p>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Welcome To My Channel Code Sphere"
        android:textAlignment="center"
        android:textSize="30sp"
        android:textColor="@android:color/black"/>



    <Button
        android:layout_width="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_height="wrap_content"
        android:text="sign out"
        android:textColor="@android:color/white"
        android:background="@android:color/black"
        android:textSize="20sp"
        android:padding="10dp"
        android:id="@+id/Button_sign_out"/>
</LinearLayout>

otpActivity-----------------------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".otpactivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter otp"
        android:textColor="@android:color/black"
        android:textSize="30sp"
        />


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="verification Code"
        android:id="@+id/verificattion_code_et"
        android:layout_margin="40dp"
        android:inputType="number"
        android:textSize="20sp"
        android:textColorHint="@android:color/black"
        android:backgroundTint="@android:color/black"
        android:textColor="@android:color/black"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/Button_otp"
        android:background="@android:color/black"
        android:textColor="@android:color/white"
        android:textSize="20sp"
        android:text="submit"
        android:padding="10dp"/>

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"
        android:layout_marginTop="20dp"
        android:id="@+id/otp_progress_bar"/>


</linearlayout>

PhoneNumber activityxml -----------------------------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="#fff"
    tools:context=".PhoneNumber">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Mobile Authentication"
        android:textSize="20sp"
        android:textAlignment="center"
        android:textColor="@android:color/black"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Please Enter your Mobile Number and country code "
        android:textSize="20sp"
        android:textAlignment="center"
        android:textColor="@android:color/holo_blue_dark"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">


        <EditText
            android:layout_width="wrap_content"
            android:layout_height="60dp"
            android:text="91"
            android:textSize="30sp"
            android:backgroundTint="@android:color/black"
            android:id="@+id/country_code_et"/>

        <EditText
            android:layout_width="300dp"
            android:layout_height="60dp"
            android:hint="Mobile Number"
            android:textColorHint="@android:color/black"
            android:textColor="@android:color/black"
            android:layout_marginLeft="10dp"
            android:textSize="30sp"
            android:inputType="phone"
            android:backgroundTint="@android:color/black"
            android:id="@+id/Mobile_Number_et"/>

    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Generate otp"
        android:background="@android:color/black"
        android:textColor="@android:color/white"
        android:padding="15dp"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:id="@+id/button_generate_otp"
        />

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"
        android:layout_marginTop="5dp"
        android:id="@+id/generate_progress_bar"/>
</LinearLayout>

MainActivity.java -------------------------------------------- -------------------------------------------------- -------------

package com.example.codesphere;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;


public class MainActivity extends AppCompatActivity {

private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
Button mSignOut;

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

    mSignOut = findViewById(R.id.Button_sign_out);
    mAuth = FirebaseAuth.getInstance();
    mCurrentUser = mAuth.getCurrentUser();

    mSignOut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mAuth.signOut();
            sendUserLogin();
        }
    });
}

private void sendUserLogin(){
    Intent HomeiNtent = new Intent(MainActivity.this,PhoneNumber.class);
    HomeiNtent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    HomeiNtent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(HomeiNtent);
    finish();
}




}

PhoneNumber .java -------------------------------------------- -------------------------------------------------- ----------------------------------

package com.example.codesphere;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ViewUtils;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
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 PhoneNumber extends AppCompatActivity {



  private EditText mCountrycode;
  private EditText mPhoneNumber;

  private Button mGeneratbtn;
  private ProgressBar mLoginProgress;

  private FirebaseUser mCurrentUser;
  private  FirebaseAuth mAuth;

  private PhoneAuthProvider.OnVerificationStateChangedCallbacks McallBack;



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

        mCountrycode = findViewById(R.id.country_code_et);
        mPhoneNumber = findViewById(R.id.Mobile_Number_et);
        mGeneratbtn = findViewById(R.id.button_generate_otp);
        mLoginProgress = findViewById(R.id.generate_progress_bar);

        mAuth = FirebaseAuth.getInstance();
        mCurrentUser = mAuth.getCurrentUser();


        mGeneratbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String country_code = mCountrycode.getText().toString();
                String phone_number = mPhoneNumber.getText().toString();

                String complete_phone_number = "+"+country_code + phone_number;

                if (country_code.isEmpty() || phone_number.isEmpty() ){
                    Toast.makeText(getApplicationContext(),"Please Fill",Toast.LENGTH_LONG).show();
                }else {
                    mLoginProgress.setVisibility(View.VISIBLE);

                    PhoneAuthProvider.getInstance().verifyPhoneNumber(
                            complete_phone_number,
                            60,
                            TimeUnit.SECONDS,
                            PhoneNumber.this,
                             McallBack
                    );
                }
            }
        });
        McallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
                 signInWithPhoneAuthCredentials(phoneAuthCredential);
            }



            @Override
            public void onVerificationFailed(@NonNull FirebaseException e) {

                Toast.makeText(getApplicationContext(),"verification Failed",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                super.onCodeSent(s, forceResendingToken);

                Intent otpIntent = new Intent(PhoneNumber.this,otpactivity.class);
                otpIntent.putExtra("AuthCredentials",s);
                startActivity(otpIntent);

            }
        };



    }

    private void signInWithPhoneAuthCredentials(PhoneAuthCredential credential){
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(PhoneNumber.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){
                            sendUserhome();
                        }else {
                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException){
                                Toast.makeText(getApplicationContext(),"error In verifying OTP",Toast.LENGTH_LONG).show();
                            }
                        }
                        mLoginProgress.setVisibility(View.VISIBLE);
                    }
                });
    }

    private void sendUserhome(){
        Intent homeIntent = new Intent(PhoneNumber.this,MainActivity.class);
        homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(homeIntent);
        finish();
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (mCurrentUser != null){
            sendUserhome();
        }

    }
}

OtpActivity.java -------------------------------------------- -------------------------------------------------- --------------------------

package com.example.codesphere;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Process;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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 otpactivity extends AppCompatActivity {


    private FirebaseAuth mAuth;
    private FirebaseUser mCurrentUser;

    private  EditText mOtpText;
    private Button mVerifybtn;

    private ProgressBar verifyProgressBar;
    private String mAuthVerificationId;


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

        mOtpText = findViewById(R.id.verificattion_code_et);
        mVerifybtn = findViewById(R.id.Button_otp);
        verifyProgressBar = findViewById(R.id.otp_progress_bar);

        mAuth = FirebaseAuth.getInstance();
        mCurrentUser = mAuth.getCurrentUser();

        mAuthVerificationId = getIntent().getStringExtra("AuthCredentials");

        mVerifybtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String otp = mOtpText.getText().toString();
                if (otp.isEmpty()){
                    Toast.makeText(getApplicationContext(),"Please fill ",Toast.LENGTH_LONG).show();
                }else
                {
                    verifyProgressBar.setVisibility(View.VISIBLE);

                    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mAuthVerificationId,otp);
                    signInWithOhoneAuthCredential(credential);
                }
            }
        });


    }
    private void signInWithOhoneAuthCredential(PhoneAuthCredential credential){
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(otpactivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){
                            senduserHome();
                        }else {
                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException){
                                Toast.makeText(getApplicationContext(),"Error in Verifying OTP",Toast.LENGTH_LONG).show();
                            }
                        }
                        verifyProgressBar.setVisibility(View.INVISIBLE);
                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (mCurrentUser != null){
            senduserHome();
        }

    }

    private void senduserHome(){
        Intent HomeiNtent = new Intent(otpactivity.this,MainActivity.class);
        HomeiNtent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        HomeiNtent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(HomeiNtent);
        finish();
    }
}

依赖关系---------------------------------------------- -------------------------------------------------- -------------------------------------

 implementation 'com.google.firebase:firebase-analytics:17.3.0''
  implementation 'com.google.firebase:firebase-auth:19.3.0'

Mainfest.xml ------------------------------------------------ -------------------------------------------------- ----------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.codesphere">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".otpactivity"></activity>
        <activity android:name=".MainActivity" />
        <activity android:name=".PhoneNumber">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


    </application>

</manifest>

0 个答案:

没有答案