Friday, November 17, 2017

Firebase google auth-

package com.edupointbd.amirul.firebase;


import android.content.Intent;
import android.os.Bundle;
import android.service.carrier.CarrierMessagingService;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

public class MainActivity extends AppCompatActivity {

    // TAG is for show some tag logs in LOG screen.    public static final String TAG = "MainActivity";

    // Request sing in code. Could be anything as you required.    public static final int RequestSignInCode = 7;

    // Firebase Auth Object.    public FirebaseAuth firebaseAuth;

    // Google API Client object.    public GoogleApiClient googleApiClient;

    // Sing out button.    Button SignOutButton;

    // Google Sign In button .    com.google.android.gms.common.SignInButton signInButton;

    // TextView to Show Login User Email and Name.    TextView LoginUserName, LoginUserEmail;


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


        signInButton = (SignInButton) findViewById(R.id.sign_in_button);

        SignOutButton= (Button) findViewById(R.id.sign_out);

        LoginUserName = (TextView) findViewById(R.id.textViewName);

        LoginUserEmail = (TextView) findViewById(R.id.textViewEmail);

        signInButton = (com.google.android.gms.common.SignInButton)findViewById(R.id.sign_in_button);

        // Getting Firebase Auth Instance into firebaseAuth object.        firebaseAuth = FirebaseAuth.getInstance();

        // Hiding the TextView on activity start up time.        LoginUserEmail.setVisibility(View.GONE);
        LoginUserName.setVisibility(View.GONE);

        // Creating and Configuring Google Sign In object.        GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        // Creating and Configuring Google Api Client.        googleApiClient = new GoogleApiClient.Builder(MainActivity.this)
                .enableAutoManage(MainActivity.this , new GoogleApiClient.OnConnectionFailedListener() {
                    @Override                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

                    }
                } /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
                .build();


        // Adding Click listener to User Sign in Google button.        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                UserSignInMethod();

            }
        });

        // Adding Click Listener to User Sign Out button.        SignOutButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                UserSignOutFunction();

            }
        });

    }


    // Sign In function Starts From Here.    public void UserSignInMethod(){

        // Passing Google Api Client into Intent.        Intent AuthIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);

        startActivityForResult(AuthIntent, RequestSignInCode);
    }

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RequestSignInCode){

            GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

            if (googleSignInResult.isSuccess()){

                GoogleSignInAccount googleSignInAccount = googleSignInResult.getSignInAccount();

                FirebaseUserAuth(googleSignInAccount);
            }

        }
    }

    public void FirebaseUserAuth(GoogleSignInAccount googleSignInAccount) {

        AuthCredential authCredential = GoogleAuthProvider.getCredential(googleSignInAccount.getIdToken(), null);

        Toast.makeText(MainActivity.this,""+ authCredential.getProvider(),Toast.LENGTH_LONG).show();

        firebaseAuth.signInWithCredential(authCredential)
                .addOnCompleteListener(MainActivity.this, new OnCompleteListener() {
                    @Override                    public void onComplete(@NonNull Task AuthResultTask) {

                        if (AuthResultTask.isSuccessful()){

                            // Getting Current Login user details.                            FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();

                            // Showing Log out button.                            SignOutButton.setVisibility(View.VISIBLE);

                            // Hiding Login in button.                            signInButton.setVisibility(View.GONE);

                            // Showing the TextView.                            LoginUserEmail.setVisibility(View.VISIBLE);
                            LoginUserName.setVisibility(View.VISIBLE);

                            Intent i = new Intent(getApplicationContext(),Welcome.class);
                            i.putExtra("name",firebaseUser.getDisplayName().toString());
                            i.putExtra("email",firebaseUser.getEmail().toString());
                            startActivity(i);

                            // Setting up name into TextView.                           // LoginUserName.setText("NAME =  "+ firebaseUser.getDisplayName().toString());
                            // Setting up Email into TextView.                           // LoginUserEmail.setText("Email =  "+ firebaseUser.getEmail().toString());
                        }else {
                            Toast.makeText(MainActivity.this,"Something Went Wrong",Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    public void UserSignOutFunction() {

        // Sing Out the User.        firebaseAuth.signOut();

        Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(
                new ResultCallback() {
                    @Override                    public void onResult(@NonNull Result result) {
                        // Write down your any code here which you want to execute After Sign Out.
                        // Printing Logout toast message on screen.                        Toast.makeText(MainActivity.this, "Logout Successfully", Toast.LENGTH_LONG).show();
                    }

                });

        // After logout Hiding sign out button.        SignOutButton.setVisibility(View.GONE);

        // After logout setting up email and name to null.        LoginUserName.setText(null);
        LoginUserEmail.setText(null);

        // After logout setting up login button visibility to visible.        signInButton.setVisibility(View.VISIBLE);
    }

}





<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:padding="20dp"    tools:context="com.edupointbd.amirul.firebase.MainActivity">

    <com.google.android.gms.common.SignInButton        android:id="@+id/sign_in_button"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_centerVertical="true"        android:layout_centerHorizontal="true" />

    <Button        android:id="@+id/sign_out"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Click Here To Sign Out"        android:layout_alignParentBottom="true"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true"        android:visibility="gone"        />

    <TextView
        android:id="@+id/textViewName"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:text=""        android:gravity="center"        android:textSize="20dp"        android:textColor="#000"        />

    <TextView
        android:id="@+id/textViewEmail"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_below="@+id/textViewName"        android:text=""        android:gravity="center"        android:textSize="20dp"        android:textColor="#000"        />

</RelativeLayout>




package com.edupointbd.amirul.firebase;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Welcome extends AppCompatActivity {

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



<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_welcome"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.edupointbd.amirul.firebase.Welcome">

    <TextView        android:id="@+id/name"        android:text="amirul"        android:textSize="22sp"        android:layout_width="match_parent"        android:layout_height="wrap_content" />
    <TextView        android:id="@+id/email"        android:textSize="22sp"        android:text="amirul@gmail.com"        android:layout_width="match_parent"        android:layout_height="wrap_content" />

</RelativeLayout>





 dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }
}


 packagingOptions{
        exclude 'META-INF/LICENSE'        exclude 'META-INF/LICENSE-FIREBASE.txt'        exclude 'META-INF/NOTICE'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'    })
    compile 'com.android.support:appcompat-v7:25.3.1'    compile 'com.google.firebase:firebase-core:9.8.0'    compile 'com.google.firebase:firebase-auth:9.8.0'    compile 'com.google.android.gms:play-services-auth:9.8.0'    testCompile 'junit:junit:4.12'}

apply plugin: 'com.google.gms.google-services'