ads

Breaking News

Phone Authentication in Android | How to Login with Mobile Number

Mobile number authentication









Phone Authentication or Login With Mobile Number!!


activity.xml 

<LinearLayout 
            android:layout_width="match_parent"    
            android:layout_height="match_parent"    
            android:orientation="vertical"
            xmlns:android="http://schemas.android.com/apk/res/android" >

         <LinearLayout
                 android:layout_width="match_parent"  
                 android:layout_height="100dp"
                 android:gravity="center"    
                 android:background="@color/colorPrimary"        >
                <TextView  
                        android:layout_width="wrap_content"    
                        android:layout_height="wrap_content"   
                        android:textColor="#fff"
                        android:text="Welcome to Pvjsca"  
                        android:textSize="22sp"
                        android:fontFamily="serif"            />
         </LinearLayout>

         <EditText
                 android:layout_width="wrap_content" 
                 android:layout_height="wrap_content"   
                 android:layout_marginTop="80dp"
                 android:ems="12" 
                 android:id="@+id/phone"   
                 android:layout_gravity="center" 
                 android:hint="Enter Mobile Number"
                 android:textAlignment="center"   
                 android:inputType="phone" 
                 android:fontFamily="sans-serif-condensed"        />
        <EditText 
                 android:layout_width="wrap_content"  
                 android:layout_height="wrap_content"
                 android:layout_marginTop="40dp" 
                 android:ems="12"   
                 android:id="@+id/otp" 
                 android:layout_gravity="center"    
                 android:hint="Enter OTP"     
                 android:textAlignment="center"    
                 android:inputType="text"  
                 android:fontFamily="sans-serif-condensed"        />
        <LinearLayout
                 android:layout_width="match_parent"    
                 android:layout_weight="1"  
                 android:gravity="bottom"  
                 android:layout_height="0dp">

        <Button     
                 android:text="Send OTP"  
                 android:background="#3131c6"  
                 android:textColor="#fff" 
                 android:id="@+id/sendButton"
                 android:layout_width="match_parent"
                android:layout_height="wrap_content" />
      </LinearLayout>
</LinearLayout>



Phone Authentication in Android | How to Login with Mobile Number
Login Page



MainActivity.java




package b.pvijay.demoviewpager;

import android.content.Intent;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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 MainActivity extends AppCompatActivity {
    private EditText phone, otp;
    private Button send;
    boolean flag=true;
    private String mVerificationId;
    private PhoneAuthProvider.ForceResendingToken toke;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener authStateListener;
    private PhoneAuthProvider.OnVerificationStateChangedCallbacks onVerificationStateChangedCallbacks;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        phone = findViewById(R.id.phone);
        otp = findViewById(R.id.otp);
        otp.setVisibility(View.INVISIBLE);
        mAuth = FirebaseAuth.getInstance();
        send = findViewById(R.id.sendButton);
        authStateListener = new FirebaseAuth.AuthStateListener() {
            @Override            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                    if(mAuth.getCurrentUser()!=null){
                        startActivity(new Intent(MainActivity.this,Home.class));
                        finish();
                    }
            }
        };
        onVerificationStateChangedCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override            public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                signInWithPhoneAuthCredential(phoneAuthCredential);
            }

            @Override            public void onVerificationFailed(FirebaseException e) {
                Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();

            }


            public void onCodeSent(String verificationId,
                                   PhoneAuthProvider.ForceResendingToken token) {
                

                // Save verification ID and resending token so we can use them later               
               mVerificationId = verificationId;
                toke = token;
                flag = false;
                phone.setVisibility(View.INVISIBLE);
                otp.setVisibility(View.VISIBLE);
                send.setEnabled(true);
                send.setText("Verify Code");


                // ...            }

        };
        send.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                if (flag) {
                    String phoneNumber = phone.getText().toString();
                    if (phoneNumber.isEmpty()) {
                        phone.setError("Empty");
                        phone.requestFocus();
                    } else {
                        send.setEnabled(false);
                        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                                phoneNumber,
                                60,
                                TimeUnit.SECONDS,   // Unit of timeout                                
                                MainActivity.this,               // Activity (for callback binding)                               
                                onVerificationStateChangedCallbacks);
                    }

                }
                else{

                        String o = otp.getText().toString();
                        if(o.isEmpty()){
                            otp.setError("Empty");
                            otp.requestFocus();
                        }
                        else{
                            send.setEnabled(false);
                            PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, o);
                            signInWithPhoneAuthCredential(credential);
                        }


            }

            }

        });

    }
    public void onStart(){
        super.onStart();
        mAuth.addAuthStateListener(authStateListener);
    }



    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                          
                           startActivity(new Intent(MainActivity.this,Home.class));
                           finish();
                            // ...                        } else {
                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                Toast.makeText(MainActivity.this,"Verification Code Is Invalid",Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                });
    }
    public void onStop(){
        super.onStop();
        mAuth.removeAuthStateListener(authStateListener);

    }



}



Manifest.xml

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

    <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=".MainActivity">
            <intent-filter>
                 <action android:name="android.intent.action.MAIN" />

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

</manifest>


activity_home.xml

<LinearLayout android:layout_width="match_parent"    
              android:layout_height="match_parent"
              android:orientation="vertical" 
              android:gravity="center"  
              xmlns:android="http://schemas.android.com/apk/res/android" >\

    <Button        
              android:layout_width="wrap_content" 
              android:layout_height="wrap_content"  
              android:text="LogOut"    
              android:id="@+id/sign"   
              android:fontFamily="sans-serif-condensed"
        />
</LinearLayout>


Home.java
package b.pvijay.demoviewpager;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.firebase.auth.FirebaseAuth;

public class Home extends AppCompatActivity {
    private Button button;
    private FirebaseAuth auth;
    private FirebaseAuth.AuthStateListener authStateListener;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        auth = FirebaseAuth.getInstance();
        button = findViewById(R.id.sign);
        button.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                auth.signOut();
            }
        });
        authStateListener = new FirebaseAuth.AuthStateListener() {
            @Override            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if(auth.getCurrentUser()==null){
                    startActivity(new Intent(Home.this,MainActivity.class));
                    finish();
                }
            }
        };

    }
    public void onStart(){
        super.onStart();
        auth.addAuthStateListener(authStateListener);
    }
    public void onStop(){
        super.onStop();
        auth.removeAuthStateListener(authStateListener);
    }
}

No comments