Airo Global Software

Think Beyond Future !

Android

Android is a mobile/desktop operating system based on a modified version of the Linux kernel and other open source software, designed primarily for touchscreen mobile devices such as smartphones and tablets.

enter image description here

There are multiple social login features to use in Android apps. Here we will know about social login using Facebook, so we need to integrate the Facebook SDK in the project to make use of Facebook login.

What are the steps needed to build a Facebook login page?

First thing you need to do is to have a Facebook developer account and then build a new app. Install android studio and open or create a new project where you want to include Facebook login. In your project, include the following code in your Project.

buildscript{
    repositories {
        jcenter()
    }
}

Now, add the following code in Module:app with the new version of Facebook Login SDK in it.

dependencies {
     implementation 'com.facebook.android:facebook-android-sdk:5.0.0'
}

Sync the project Now start with app -> res -> values -> strings.xml file to include the lines and replace the [APP_ID] with your APP_ID, which you can get from Facebook Developer console. Open app -> manifest -> manifest file and add this line outside of the application. Include the meta-data element inside the app element in AndroidManifest.xml file. Now first thing you need is Key Hash, so include these lines in the activity class before Facebook login code:

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

...
  
    public void
    printHashKey()
{
  
    // Add code to print out the key hash
    try {
  
        PackageInfo info
            = getPackageManager().getPackageInfo(
                "com.android.facebookloginsample",
                PackageManager.GET_SIGNATURES);
  
        for (Signature signature : info.signatures) {
  
            MessageDigest md
                = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:",
                  Base64.encodeToString(                      md.digest(),
                      Base64.DEFAULT));
        }
    }
  
    catch (PackageManager.NameNotFoundException e) {
    }
  
    catch (NoSuchAlgorithmException e) {
    }
}

Now run the application. You will see Key Hash value in logcat, save this for later needs. Go to Facebook Developers console and choose setting -> Basic -> Add Platform and a popup will open up to select a platform. Select Android as a platform. Include your project package name under ‘Google Play Package Name’. Add the class name where login will be implemented in projects like ‘LoginActivity’ and also include the key hash value under ‘Key Hashes’. Now in android studio, include this personalised button in your *.xml layout file:

Include this code in app -> res -> styles.xml :

You can personalize this button instead of an above custom button, you can use the Facebook button also as Facebook LoginButton. Make a file named ‘bg_button_facebook.xml’ in app -> res -> drawable folder Now make a button in *.java file and some syntax to initialize Facebook SDK :

// Declare variables
private Button mButtonFacebook;
  
private CallbackManager callbackManager;
private LoginManager loginManager;
 ...
      @Override
    protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
     ...
          mButtonFacebook
        = findViewById(R.id.button_facebook);
    FacebookSdk.sdkInitialize(MainActivity.this);
    callbackManager = CallbackManager.Factory.create();
    facebookLogin();
    ...
          mButtonFacebook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                loginManager.logInWithReadPermissions(
                    MainActivity.this,
                    Arrays.asList(
                        "email",
                        "public_profile",
                        "user_birthday"));
            }
        });
    ...
}
 ...

Add ‘facebookLogin’ option outside onCreate() in the java file. This is the program code for Facebook login response.

public void facebookLogin()
{
      loginManager
        = LoginManager.getInstance();
    callbackManager
        = CallbackManager.Factory.create();
      loginManager
        .registerCallback(
            callbackManager,
            new FacebookCallback() {
                  @Override
                public void onSuccess(LoginResult loginResult)
                {
                    GraphRequest request = GraphRequest.newMeRequest(
                          loginResult.getAccessToken(),
                         new GraphRequest.GraphJSONObjectCallback() {
                              @Override
                            public void onCompleted(JSONObject object,
                                                    GraphResponse response)
                            {
                                  if (object != null) {
                                    try {
                                        String name = object.getString("name");
                                        String email = object.getString("email");
                                        String fbUserID = object.getString("id");
                                          disconnectFromFacebook();
  
                                        // do action after Facebook login success
                                        // or call your API
                                    }
                                    catch (JSONException | NullPointerException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
  
                    Bundle parameters = new Bundle();
                    parameters.putString(
                        "fields",
                        "id, name, email, gender, birthday");
                    request.setParameters(parameters);
                    request.executeAsync();
                }
                  @Override
                public void onCancel()
                {
                    Log.v("LoginScreen", "---onCancel");
                }
                  @Override
                public void onError(FacebookException error)
                {
                    // here write code when get error
                    Log.v("LoginScreen", "----onError: "
                                             + error.getMessage());
                }
            });
}

Now include another needed option ‘disconnectFromFacebook’ for login , similarly add this to onCreate. This is used to disconnect applications from Facebook as there is no need to stay connected.

public void disconnectFromFacebook()
{
    if (AccessToken.getCurrentAccessToken() == null) {
        return; // already logged out
    }
  
    new GraphRequest(
        AccessToken.getCurrentAccessToken(),
        "/me/permissions/",
        null,
        HttpMethod.DELETE,
        new GraphRequest
            .Callback() {
                @Override
                public void onCompleted(GraphResponse graphResponse)
                {
                    LoginManager.getInstance().logOut();
                }
            })
        .executeAsync();
}

Include ‘onActivityResult’ option onCreate in same activity:

@Override
protected void onActivityResult(int requestCode,
                                int resultCode,
                                Intent data)
{
      // add this line
    callbackManager.onActivityResult(
        requestCode,
        resultCode,
        data);
      super.onActivityResult(requestCode,
                           resultCode,
                           data);
}

Now you are finished with the coding. Run your application in your emulator. You can now login with Facebook also in your application. If you have any questions about the above topic or have to get services and consultations and get the best Android application services. Feel free to contact us. AIRO GLOBAL SOFTWARE will be your strong digital partner. E-mail id: [email protected]

enter image description here Author - Johnson Augustine
Chief Technical Director and Programmer
Founder: Airo Global Software Inc
LinkedIn Profile: www.linkedin.com/in/johnsontaugustine/

enter image description here

In this blog, we will integrate the Firebase Authentication for Google Sign-In in our Android application using Google and Firebase APIs.

What is firebase authentication?

Firebase Authentication ensures backend services for we can simply use the SDKs and in-built UI libraries to authenticate the person that is used in the android app. Most of the apps need the identity of the person that is using, and after knowing their activity status, the app saves the user's data safely in the cloud. It targets building a safe authentication system.

Using Firebase Authentication, we will authenticate the log-in of Google, Facebook, GitHub and more.

What are the steps to create and configure the android app on the google firebase account?

  • The first step is to create a firebase developer account and after installing it ‘Go to console’.
  • Select the option 'Add project'.
  • Complete the project name and select the analytics area, cloud Firestore location, accept the controller terms and select 'Create project'.
  • When your new project is completely ready select 'Continue'.
  • The next step is to click on the android platform SDK.
  • The next step is to Register your app to Firebase by providing the required app information and clicking on 'Register app'.
  • The next step is to download the 'google-services.json' file to integrate it into the Android app and select 'Next.
  • The next step is to add the Firebase SDK dependencies in the .gradle folders of your app and select 'Sync now' in the IDE and select the option 'Next'.

BUILD GRADLE (PROJECT):

dependencies { 
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:4.0.1'
// in the individual module build. Gradle files  
}

BUILD GRADLE(MODULE):

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])  
 implementation 'com.android.support:appcompat-v7:27.1.1'
  implementation 'com.android.support.constraint:constraint-layout:1.1.3'
 testImplementation 'junit:junit:4.12'
 androidTestImplementation 'com.android.support.test:runner:1.0.2' 
androidTestImplementation 
'com.android.support.test.espresso:espresso-core:3.0.2' 
implementation 'com.google.firebase:firebase-auth:16.0.3' 
 implementation 'com.google.firebase:firebase-core:16.0.3'
 implementation 'com.google.android.gms:play-services-auth:16.0.0'  
  implementation 'com.github.bumptech.glide:glide:3.7.0' 
}
apply : 'com.google.gms.google-services' 

What should I do in androidmanifest.xml?

First, add internet permission:
<uses-permission android:name="android.permission.INTERNET" />
  • Execute your app to verify the installation configuration, if everything is alright it shows a success message and then select the 'Continue to console'.
  • Next step you need to know that on the console page click on Authentication -gt; Sign-in method -gt;Google -gt; Enable and at last select on 'Save'.

Give an example of android firebase authentication with a google sign-in example?

Add the below code in an activity_main.xml file. In this activity, we use the custom Google Sign-in button:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 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" 
tools:context="example.javatpoint.com.firebasegooglelogin.MainActivity">
   <TextView 
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" 
android:textSize="20dp"
 android:text="This is main activity, sign in to move next activity." /> 

   <com.google.android.gms.common.SignInButton
android:layout_width="match_parent"
 android:layout_height="wrap_content"
android:id="@+id/sign_in_button"
 android:layout_marginLeft="20dp" 
android:layout_marginRight="20dp" 
 android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp">
  </com.google.android.gms.common.SignInButton>
</RelativeLayout> 

The next step is to add your web client id in the string.xml file.

<resources>
<string name="app_name">Firebase Google Login</string>
<string name="web_client_id">xxxxxxxx..place your web client id </string>
</resources> 

Next, add the below code in MainActivity.java class

package example.javatpoint.com.firebasegooglelogin;
import android.content.Intent; 
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; 
import android.util.Log;
import android.view.View; 
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.tasks.OnCompleteListener; 
import com.google.android.gms.tasks.Task; 
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult; 
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;  
import com.google.firebase.auth.GoogleAuthProvider; 

OnConnectionFailedListener {  

   private static final String TAG = "MainActivity";  
private SignInButton signInButton;
private GoogleApiClient googleApiClient; 
private static final int RC_SIGN_IN = 1;
String name, email; 
  String idToken; 
private FirebaseAuth firebaseAuth;
 private FirebaseAuth.AuthStateListener authStateListener; 

@Override
protected void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main);  
firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance(); 
 authStateListener = new FirebaseAuth.AuthStateListener(){  
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
  // Get signedIn user 
FirebaseUser user = firebaseAuth.getCurrentUser(); 
//if user is signed in, we call a helper method to save the user details to Firebase 
if (user != null) { 
// User is signed in 
 Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());  
 } else { 
// User is signed out
 Log.d(TAG, "onAuthStateChanged:signed_out");  
}
  }  
 };

GoogleSignInOptions gso =  new
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
.requestIdToken(getString(R.string.web_client_id))//you can also use R.string.default_web_client_id
 .requestEmail()
.build(); 
 googleApiClient=new GoogleApiClient.Builder(this)
 .enableAutoManage(this,this)
.addApi(Auth.GOOGLE_SIGN_IN_API,gso)
 .build(); 

signInButton = findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {  
@Override 
public void onClick(View view) {  
 Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient); 
startActivityForResult(intent,RC_SIGN_IN); 
 }  
 });  
  } 

@Override
public void onConnectionFailed(@NonNull ConnectionResult
connectionResult) { 
  }  
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
 super.onActivityResult(requestCode, resultCode, data); 
 if(requestCode==RC_SIGN_IN){ 
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);  
 } 
 }

private void handleSignInResult(GoogleSignInResult result){  
 if(result.isSuccess()){
GoogleSignInAccount account = result.getSignInAccount();
  idToken = account.getIdToken();
 name = account.getDisplayName(); 
 email = account.getEmail(); 
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null); 
firebaseAuthWithGoogle(credential); 
 }else{  

Log.e(TAG, "Login Unsuccessful. "+result); 
Toast.makeText(this, "Login Unsuccessful", Toast.LENGTH_SHORT).show();
 }
 } 
 private void firebaseAuthWithGoogle(AuthCredential credential){ 
firebaseAuth.signInWithCredential(credential)
 .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
 @Override
 public void onComplete(@NonNull Task<AuthResult> task) {

Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

   if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Login successful", Toast.LENGTH_SHORT).show(); 
gotoProfile();
  }else{  
   Log.w(TAG, "signInWithCredential" + task.getException().getMessage()); 
 task.getException().printStackTrace();
  Toast.makeText(MainActivity.this, "Authentication failed.",  
                                Toast.LENGTH_SHORT).show();
  }  
 }
 });
}
  private void gotoProfile(){ 
 Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
 startActivity(intent);  
 finish();
 } 
 @Override
 protected void onStart() {  
super.onStart();
  if (authStateListener != null){  
 FirebaseAuth.getInstance().signOut();
 }
  firebaseAuth.addAuthStateListener(authStateListener); 
 } 
@Override 
  protected void onStop() {
super.onStop(); 
 if (authStateListener != null){ 
firebaseAuth.removeAuthStateListener(authStateListener);
 }
 }
 }

The next step is to add the below code in the profile_activity.xml file:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 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"  
tools:context="example.javatpoint.com.firebasegooglelogin.ProfileActivity">
    <LinearLayout
 android:layout_width="match_parent" 
android:layout_height="match_parent"
 android:gravity="center"
 android:orientation="vertical">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="@+id/profileImage" 
   /> 
  <TextView  
android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:id="@+id/name" 
android:text="name" 
 android:textSize="20dp"
android:layout_marginTop="20dp"/>
   <TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" 
android:id="@+id/email"
android:textSize="20dp"
android:text="email"
 android:layout_marginTop="20dp"/>  
  <TextView  

android:layout_width="wrap_content"

android:layout_height="wrap_content"
 android:id="@+id/userId" 
android:textSize="20dp"
 android:text="id" 
android:layout_marginTop="20dp"/>
<Button
android:layout_width="wrap_content" 
android:layout_height="wrap_content"
android:id="@+id/logoutBtn"
 android:text="Logout"
android:layout_marginTop="30dp"/> 
 </LinearLayout> 
</RelativeLayout>

Next, we have to add profileActivity.java

package example.javatpoint.com.firebasegooglelogin;
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 android.widget.ImageView; 
import android.widget.TextView; 
import android.widget.Toast;

import com.bumptech.glide.Glide;
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.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;  
import com.google.android.gms.common.api.ResultCallback;  
import com.google.android.gms.common.api.Status;
import com.google.firebase.auth.FirebaseAuth;  

public class ProfileActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener { 
Button logoutBtn;
TextView userName,userEmail,userId;
 ImageView profileImage; 
private GoogleApiClient googleApiClient;
private GoogleSignInOptions gso;  
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile); 
  logoutBtn = findViewById(R.id.logoutBtn); 
userName = findViewById(R.id.name);
userEmail = findViewById(R.id.email);
 userId = findViewById(R.id.userId); 
profileImage = findViewById(R.id.profileImage); 
gso =  new 
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
.requestEmail() 
 .build();  
  googleApiClient=new GoogleApiClient.Builder(this) 
 .enableAutoManage(this,this)
 .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
 .build();  
    logoutBtn.setOnClickListener(new View.OnClickListener() {  
  @Override  
 public void onClick(View view) { 
 FirebaseAuth.getInstance().signOut();
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(
 new ResultCallback<Status>() { 
 @Override
 public void onResult(Status status) { 
 if (status.isSuccess()){ 
gotoMainActivity();
 }else{ 
Toast.makeText(getApplicationContext(),"Session not close",Toast.LENGTH_LONG).show(); 
}
} 
 });
 }
  });  
 }
 @Override 
 protected void onStart() {
 super.onStart();
OptionalPendingResult<GoogleSignInResult> opr= Auth.GoogleSignInApi.silentSignIn(googleApiClient);  
  if(opr.isDone()){  
GoogleSignInResult result=opr.get();  
handleSignInResult(result); 
  }else{
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() { 
@Override
 public void onResult(@NonNull GoogleSignInResult googleSignInResult)
{ 
handleSignInResult(googleSignInResult);
  } 
});  
  }
  }
  private void handleSignInResult(GoogleSignInResult result){  
  if(result.isSuccess()){
GoogleSignInAccount account=result.getSignInAccount();  
userName.setText(account.getDisplayName());
userEmail.setText(account.getEmail());  
 userId.setText(account.getId());
try{
Glide.with(this).load(account.getPhotoUrl()).into(profileImage);  
  }catch (NullPointerException e){ 
Toast.makeText(getApplicationContext(),"image not found",Toast.LENGTH_LONG).show(); 
 }
 }else{  
gotoMainActivity(); 
}  
}  
private void gotoMainActivity(){ 
 Intent intent=new Intent(this,MainActivity.class); 
startActivity(intent); 
} 
@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {  
   } 
   } 

If you have any questions about the above topic or have to get services and consultations and get the best android application development services. Feel free to contact us. AIRO GLOBAL SOFTWARE will be your strong digital partner. E-mail id: [email protected]

enter image description here Author - Johnson Augustine
Chief Technical Director and Programmer
Founder: Airo Global Software Inc
LinkedIn Profile: www.linkedin.com/in/johnsontaugustine/