facebook login

Part. 3 Facebook login function

Parse provides an easy way to integrate Facebook with your application. You can also implement this kind of function on back4app.

Step 1 – Setup

To start using Facebook Functions, you need to:

1. Set up a Facebook app , if you haven’t already.

2.Follow Facebook’s instruction for getting started with the Facebook SDK to create an app linked to the Facebook SDK. Once you get to Step 6, stop after linking the Facebook SDK project and configuring the Facebook app ID.

3.Deleting all jar file from app/libs (you have imported this at Part 1 – Step1&2.

Because Facebook SDK and Parse Facebook Util has already contain bolt and com.parse

Otherwise, dexException will be thrown while you compile the app

4.modify your app/build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.facebook.android:facebook-android-sdk:4.9.0'
    compile 'com.parse:parsefacebookutils-v4-android:[email protected]'
    compile 'com.parse:parse-android:1.13.0'
}

5. import to your Activity

import com.parse.ParseFacebookUtils;
import com.facebook.FacebookSdk;

@Override
protected void onCreate(Bundle savedInstanceState) {
.....
FacebookSdk.sdkInitialize(getApplicationContext());
ParseFacebookUtils.initialize(this);
...}

Step 2 – Login Implementation

After Step1, you are supposed to have your own Facebook app ID and make sure you add below things.

main/res/values/string.xml
<string name="facebook_app_id">Your Facebook App ID</string>

main/AndroidManifest.xml
<application>
..
<activity android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
    android:theme="@android:style/Theme.Translucent.NoTitleBar"
    android:label="@string/app_name" />
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<provider android:authorities="com.facebook.app.FacebookContentProviderYOURAPPID"
    android:name="com.facebook.FacebookContentProvider"
    android:exported="true"/>
...
</application>

To implement Facebook Login, simply use below code:

ParseFacebookUtils.logInWithReadPermissionsInBackground(MainActivity.this, permissions, new LogInCallback() {
    @Override
    public void done(ParseUser user, ParseException err) {
        if (user == null) {
            Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
        } else if (user.isNew()) {
            Log.d("MyApp", "User signed up and logged in through Facebook!");
        } else {
            Log.d("MyApp", "User logged in through Facebook!");
        }
    }
});

I place it inside a button:

Button facebookLogin;
final List<String> permissions = Arrays.asList("public_profile", "email");
protected void onCreate(Bundle savedInstanceState) {
...
facebookLogin = (Button) findViewById(R.id.facebookButton);
facebookLogin.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ParseFacebookUtils.logInWithReadPermissionsInBackground(MainActivity.this, permissions, new LogInCallback() {
            @Override
            public void done(ParseUser user, ParseException err) {
                if (user == null) {
                    Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
                } else if (user.isNew()) {
                    Log.d("MyApp", "User signed up and logged in through Facebook!");
                    getUserDetailFromFB();
                } else {
                    Log.d("MyApp", "User logged in through Facebook!");
                    getUserDetailFromParse();
                }
            }
        });
    }
});
......
}


Layout.xml
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Facebook Login"
    android:id="@+id/facebookButton" />

For the

final List<String> permissions = Arrays.asList("public_profile", "email");

you can check other permissions from Permissions List

Step 3 – Login Refinement

As you can see, I add two more method after Facebook login. It is because the user detail could not be fetched with just using the above code.

Therefore, getUserDetailFromFB() and getUserDetailFromParse() need to be add.

PS: t_username and t_email is just a TextView, please declare them in your layout.xml and oncreate.

This is the method call from the new user login via Facebook

void getUserDetailFromFB(){
    GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),new GraphRequest.GraphJSONObjectCallback(){
        @Override
        public void onCompleted(JSONObject object, GraphResponse response) {
            try{
                t_username.setText(object.getString("name"));
            }catch(JSONException e){
                e.printStackTrace();
            }
            try{
                t_email.setText(object.getString("email"));
            }catch(JSONException e){
                e.printStackTrace();
            }
            saveNewUser();
        }
    });
    Bundle parameters = new Bundle();
    parameters.putString("fields","name,email");
    request.setParameters(parameters);
    request.executeAsync();
}
void saveNewUser(){
    ParseUser user = ParseUser.getCurrentUser();
    user.setUsername(t_username.getText().toString());
    user.setEmail(t_email.getText().toString());
    user.saveInBackground(new SaveCallback() {
        @Override
        public void done(ParseException e) {
            alertDisplayer("First Time Login Welcome", "User:" + t_username.getText().toString() + " Login.Email:" + t_email.getText().toString());
        }
    });
}
If old user login...

void getUserDetailFromParse(){
    ParseUser user = ParseUser.getCurrentUser();
    t_username.setText(user.getUsername());
    t_email.setText(user.getEmail());
    alertDisplayer("Welcome Back","User:"+t_username.getText().toString()+" Login.Email:"+t_email.getText().toString());

}

The Result will be like this.

Click Facebook login first time will direct you to Facebook App confirmation page.

Click second will just login but not asking you confirmation again.

GM_20160728_194531

Screen Shot 2016-07-28 at 7.48.30 pm

You can find your result from back4app dashboard.

PS: I don’t use this email right now. You can mail me via [email protected] if any questions.

Step 4 – Keyhash from Facebook

It is Compulsory to generate Keyhash for you Facebook APP. Otherwise, there will have some error while you login to your app via Facebook.

This tutorial will show you how to generate it in DEBUG mode NOT Release mode for this stage.

Go to https://developers.facebook.com/quickstarts/YOUR APP ID/?platform=android

Go to Key Hashes

OR Generate it by code

I try the option 1 but no luck so I generate it by code.

onCreate(...){
...
getKeyHash();
...
}

private void getKeyHash() {
    try {
        PackageInfo info = getPackageManager().getPackageInfo("scm.dominwong4.back4appandroidtutorial", 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) {
        //something
    } catch (NoSuchAlgorithmException e) {
        //something
    }
}

Screen Shot 2016-07-28 at 8.42.03 pm

Copy the key

Go to https://developers.facebook.com/apps/You APP ID/settings/

Then paste to Android -> keyhash

Screen Shot 2016-07-28 at 8.42.25 pm

Finally, test it couple of time with your app. If it doesn’t tell you any invalid key hash. It will be ok.

At this stage, you can login or register with different way. Also, you able to get user name or user email after login and display on screen.

Next, We will go to twitter login function.