Skip to content

Instantly share code, notes, and snippets.

@harshildarji
Last active December 5, 2016 19:05
Show Gist options
  • Save harshildarji/8a0a9769634ae2560eb886b5025dbf86 to your computer and use it in GitHub Desktop.
Save harshildarji/8a0a9769634ae2560eb886b5025dbf86 to your computer and use it in GitHub Desktop.
Sign-In with Facebook using Firebase and get user information using Facebook Graph API.
<?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:id="@+id/activity_facebook"
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.example.harshil.firebasebasic.facebook">
<ProgressBar
android:id="@+id/progressBar2"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/progressBar2"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="Handshaking with Facebook..."
android:textColor="@color/colorAccent"
android:textStyle="normal|bold" />
<com.facebook.login.widget.LoginButton
android:id="@+id/button_facebook_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:visibility="invisible" />
</RelativeLayout>
package com.example.harshil.firebasebasic;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
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.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
public class facebook extends AppCompatActivity {
private static final String TAG = "FacebookLogin";
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private CallbackManager mCallbackManager;
private String email, first_name, last_name, gender, birthday;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_facebook);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
Intent intent = new Intent(facebook.this, AccountActivity.class);
intent.putExtra("email", email);
intent.putExtra("first_name", first_name);
intent.putExtra("last_name", last_name);
intent.putExtra("gender", gender);
intent.putExtra("birthday", birthday);
intent.putExtra("provider", "facebook");
intent.putExtra("avatar", firebaseAuth.getCurrentUser().getPhotoUrl().toString());
startActivity(intent);
}
}
};
mCallbackManager = CallbackManager.Factory.create();
final LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions(Arrays.asList("email", "user_birthday"));
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Access Token", loginResult.getAccessToken().toString());
Log.d(TAG, "facebook:onSuccess:" + loginResult);
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
final JSONObject jsonObject = response.getJSONObject();
try {
email = jsonObject.getString("email");
first_name = jsonObject.getString("first_name");
last_name = jsonObject.getString("last_name");
gender = jsonObject.getString("gender");
birthday = jsonObject.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,first_name,last_name,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
handleFacebookAccessToken(loginResult.getAccessToken());
}
@Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
@Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.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()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(facebook.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment