Using Google Sign In with Firebase Auth in AIDE

This tutorial shows a sample project using Google Sign in in AIDE.

Step 1: Create a new project in AIDE with name MyApp and package name com.test.myapp.

Step 2: Create a new project in Firebase console. To this project add an android app with package name com.test.myapp.

Step 3: In AIDE, run the project and sign using a debug or release key.

Step 4:  Using Dev tools app find the SHA-1 of the installed app.

Step 5:  Paste the SHA-1 in Firebase console project settings.

Step 6: In Firebase Authentication — Sign-in method, enable Google.

Step 7: Download google-services.json file.

Step 8: Put the google-services.json file in app/ folder of your project.

Step 9: In app/build.gradle use following code.

apply plugin: 'com.android.application'

android {
	useLibrary 'org.apache.http.legacy'
	compileSdkVersion 28
	
	defaultConfig {
		applicationId "com.test.myapp"
		minSdkVersion 21
		targetSdkVersion 28
		versionCode 3
		versionName "1.5"
		multiDexEnabled true
	}
	buildTypes {
		release {
			minifyEnabled false
			proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
		}
	}
}

dependencies {
	implementation 'de.hdodenhof:circleimageview:3.1.0'
	implementation 'com.github.bumptech.glide:glide:3.7.0'
	compile 'android.arch.core:common:+'
	api 'com.google.android.gms:play-services-auth:16.+'
	compile fileTree(dir: 'libs', include: ['*.jar'])
	implementation 'com.google.firebase:firebase-auth:17.0.0'
	implementation 'com.google.firebase:firebase-database:17.0.0'
	implementation 'com.google.firebase:firebase-storage:17.0.0'
	
}

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

Step 10: In AndroidManifest.xml add following code.

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.myapp" >
	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
		android:resizeableActivity = "true">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
		<activity
			android:name=".HomeActivity"
			/>
		
		<meta-data
			android:name="com.google.android.gms.version"
			android:value="@integer/google_play_services_version"/>
		<!-- Use your package name in the 'android:authorities' in provider code below-->
		<provider
			android:name="com.google.firebase.provider.FirebaseInitProvider"
			android:authorities="com.test.myapp.firebaseinitprovider"
			android:exported="false"
			android:initOrder="100"/>
		<service
			android:name="com.google.firebase.components.ComponentDiscoveryService"
			android:exported="false">
			<meta-data
				android:name="com.google.firebase.components:com.google.firebase.auth.FirebaseAuthRegistrar"
				android:value="com.google.firebase.components.ComponentRegistrar"/>
			<meta-data
				android:name="com.google.firebase.components:com.google.firebase.database.DatabaseRegistrar"
				android:value="com.google.firebase.components.ComponentRegistrar"/>
			<meta-data
				android:name="com.google.firebase.components:com.google.firebase.storage.StorageRegistrar"
				android:value="com.google.firebase.components.ComponentRegistrar"/>
		</service>
		<uses-library
			android:name="org.apache.http.legacy"
			android:required="false"/>
    </application>

</manifest>

Step 11: In app/src/main/res/values/ folder add a new XML file secrets.xml. In secrets.xml, add following code.

<resources>
	<integer	name="google_play_services_version">12451000</integer>

</resources>

Step 12: In main.xml, add following code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:padding="24dp"
	android:background="#FFFFFF"
	android:gravity="center_vertical|center_horizontal"
	android:orientation="vertical">
	
		<de.hdodenhof.circleimageview.CircleImageView
			xmlns:app="http://schemas.android.com/apk/res-auto"
			android:id="@+id/imageview1"
			android:layout_width="100dp"
			android:layout_height="100dp"
			android:src="@drawable/ic_launcher"
			app:civ_border_width="1dp"
			app:civ_border_color="#FF000000"/>

		<TextView
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="WELCOME"
			android:layout_margin="10dp"
			android:textSize="30sp"
			android:textStyle="bold"
			android:textColor="#454072"
			android:elevation="10dp"/>
		
		<com.google.android.gms.common.SignInButton
			android:id="@+id/sign_in_button"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_marginBottom="60dp"
			android:layout_marginTop="20dp"/>

</LinearLayout>

Step 13: Create a new XML file home.xml. In home.xml, add following code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:orientation="vertical"
	android:gravity="center_vertical|center_horizontal">

	<de.hdodenhof.circleimageview.CircleImageView
		xmlns:app="http://schemas.android.com/apk/res-auto"
		android:id="@+id/imageview_profile_pic"
		android:layout_width="100dp"
		android:layout_height="100dp"
		android:src="@drawable/ic_launcher"
		app:civ_border_width="1dp"
		app:civ_border_color="#FF000000"/>

	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="WELCOME"
		android:layout_margin="10dp"
		android:textSize="18sp"
		android:textStyle="bold"
		android:textColor="#454072"
		android:elevation="10dp"
		android:id="@+id/textview_name"/>

	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="You have successfully logged in."
		android:textAppearance="?android:attr/textAppearanceLarge"
		android:gravity="center_horizontal"/>

	<Button
		android:layout_width="wrap_content"
		style="?android:attr/buttonBarButtonStyle"
		android:layout_height="wrap_content"
		android:text="LOG OUT"
		android:id="@+id/button_logout"/>

</LinearLayout>

Step 14: In MainActivity.java use following code.

package com.test.myapp;

import android.app.Activity;
import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.content.*;
import java.util.*;
import java.text.*;
import com.google.android.gms.auth.api.signin.*;
import com.google.android.gms.common.*;
import com.google.android.gms.common.api.*;
import com.google.firebase.auth.*;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import android.support.annotation.NonNull;

public class MainActivity extends Activity {

	public static final int RC_SIGN_IN = 1;
	SignInButton signInButton;
	public FirebaseAuth mAuth;
	GoogleSignInClient mGoogleSignInClient;
	private Intent i = new Intent();

	@Override
	protected void onCreate(Bundle _savedInstanceState) {
		super.onCreate(_savedInstanceState);
		setContentView(R.layout.main);
		com.google.firebase.FirebaseApp.initializeApp(this);

		mAuth = FirebaseAuth.getInstance();
		GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
			.requestIdToken(getString(R.string.default_web_client_id))
			.requestEmail()
			.build();

		mGoogleSignInClient = GoogleSignIn.getClient(this, googleSignInOptions);
		initialize(_savedInstanceState);
	}

	private void initialize(Bundle _savedInstanceState) {
		signInButton = findViewById(R.id.sign_in_button);
		signInButton.setSize(SignInButton.SIZE_WIDE);

		signInButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					UserSignInMethod();
				}
			});
	}
	
	@Override
	public void onStart() {
		super.onStart();
		FirebaseUser currentUser = mAuth.getCurrentUser();
		if (currentUser != null) {
			i.setClass(getApplicationContext(), HomeActivity.class);
			startActivity(i);
			finish();
		}
	}

	public void UserSignInMethod(){
		try{
			Intent signInIntent = mGoogleSignInClient.getSignInIntent();
			startActivityForResult(signInIntent, RC_SIGN_IN);
		} catch (Exception e){
			Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == RC_SIGN_IN) {
			Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
			try {
				// Google Sign In was successful, authenticate with Firebase
				GoogleSignInAccount account = task.getResult(ApiException.class);
				firebaseAuthWithGoogle(account.getIdToken());
			} catch (ApiException e) {
				// Google Sign In failed
				Toast.makeText(getApplicationContext(),"Google sign in failed " +e.toString(), Toast.LENGTH_LONG).show();
			}
		}
	}

	private void firebaseAuthWithGoogle(String idToken) {
		AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
		mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success
						i.setClass(getApplicationContext(), HomeActivity.class);
						startActivity(i);
                        finish();
                    } else {
                        // If sign in fails, display a message to the user.
                        Toast.makeText(getApplicationContext(), "signInWithCredential:failure" + task.getException(), Toast.LENGTH_LONG).show();
					}
                }
            });
	}

	
}

Step 15: Add new class HomeActivity.java. In HomeActivity.java use following code.

package com.test.myapp;

import android.app.*;
import android.os.*;
import de.hdodenhof.circleimageview.*;
import android.widget.*;
import com.google.firebase.auth.*;
import com.bumptech.glide.*;
import java.net.*;
import android.net.*;
import android.view.View.*;
import android.view.*;
import android.content.*;

public class HomeActivity extends Activity{
	
	CircleImageView profilepic;
	TextView name;
	Button logout;
	
	@Override
	protected void onCreate(Bundle _savedInstanceState) {
		super.onCreate(_savedInstanceState);
		setContentView(R.layout.home);
		com.google.firebase.FirebaseApp.initializeApp(this);
		
		profilepic = findViewById(R.id.imageview_profile_pic);
		name = findViewById(R.id.textview_name);
		logout = findViewById(R.id.button_logout);
	
		FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
		Uri photoUri = user.getPhotoUrl();
		String displayName = user.getDisplayName();
		
		name.setText(displayName);
		if (photoUri != null){
		Glide.with(getApplicationContext()).load(photoUri).into(profilepic);
		}
		
		logout.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v){
				FirebaseAuth.getInstance().signOut();
				Intent i = new Intent();
				i.setClass(getApplicationContext(), MainActivity.class);
				startActivity(i);
				finish();
			}
		});
	}
	
	
}

Step 16:
Now run the app.