how to implement facebook login in android using f

2019-01-09 07:54发布

问题:

I am trying to login with facebook using android sdk 4.7. I have tried the following link http://www.theappguruz.com/blog/android-facebook-integration-tutorial http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/

回答1:

This code works for me, try it out and check that you are using facebook sdk 4.7

package com.kushal.facebooklogin;

    import java.util.Arrays;
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.TextView;
    import com.facebook.*;
    import com.facebook.login.LoginManager;
    import com.facebook.login.LoginResult;
    import com.facebook.login.widget.LoginButton;

    public class FacebookLogin extends FragmentActivity
    {
        private TextView tvfirst_name, tvlast_namee, tvfull_name, tvEmail;
        private CallbackManager callbackManager;
        LoginButton login_button;
        String email,name,first_name,last_name;

        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            FacebookSdk.sdkInitialize(this.getApplicationContext());
            callbackManager = CallbackManager.Factory.create();

            setContentView(R.layout.main);

            tvfirst_name        = (TextView) findViewById(R.id.first_name);
            tvlast_namee        = (TextView) findViewById(R.id.last_name);
            tvfull_name         = (TextView) findViewById(R.id.full_name);
            tvEmail             = (TextView) findViewById(R.id.email);
            login_button        = (LoginButton) findViewById(R.id.login_button);

            login_button.setReadPermissions(Arrays.asList("public_profile","email"));
            login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
            {
                @Override
                public void onSuccess(LoginResult loginResult)
                {
                    login_button.setVisibility(View.GONE);

                    GraphRequest graphRequest   =   GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback()
                    {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response)
                        {
                            Log.d("JSON", ""+response.getJSONObject().toString());

                            try
                            {
                                email       =   object.getString("email");
                                name        =   object.getString("name");
                                first_name  =   object.optString("first_name");
                                last_name   =   object.optString("last_name");

                                tvEmail.setText(email);
                                tvfirst_name.setText(first_name);
                                tvlast_namee.setText(last_name);
                                tvfull_name.setText(name);
                                LoginManager.getInstance().logOut();
                            }
                            catch (JSONException e)
                            {
                                e.printStackTrace();
                            }
                        }
                    });

                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "id,name,first_name,last_name,email");
                    graphRequest.setParameters(parameters);
                    graphRequest.executeAsync();
                }

                @Override
                public void onCancel()
                {

                }

                @Override
                public void onError(FacebookException exception)
                {

                }
            });
        }

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

the xml design is as follow

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFF"
    android:gravity="center"
    android:orientation="vertical" >

    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/first_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/last_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/full_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp"
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout>

the mainefest file is as follow:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kushal.facebooklogin"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar" >
        <activity
            android:name=".FacebookLogin"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />
    </application>

</manifest>


回答2:

You can use the Facebook Android SDK. Here you have explained in the documentation how to build a Facebook Login to your app.

It says:

The simplest way to add Facebook Login to your app is to add LoginButton from the SDK. This is a custom view implementation of a Button. You can use this button in your app to implement Facebook Login.

Add the Login Button

Add the button to your layout XML file with the full class name, com.facebook.widget.LoginButton:

<com.facebook.login.widget.LoginButton
    android:id="@+id/login_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="30dp"
    android:layout_marginBottom="30dp" />

Then set up the button in your UI by adding it to a fragment and update your activity to use your fragment.

You can customize the properties of Login button and register a callback in your onCreateView() method.

Properties you can customize includes LoginBehavior, DefaultAudience, ToolTipPopup.Style and permissions on the LoginButton. For example:

@Override
public View onCreateView(
        LayoutInflater inflater,
        ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.splash, container, false);

    loginButton = (LoginButton) view.findViewById(R.id.login_button);
    loginButton.setReadPermissions("user_friends");
    // If using in a fragment
    loginButton.setFragment(this);    
    // Other app specific specialization

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
        }

        @Override
        public void onCancel() {
            // App code
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
        }
    });    
}

If you use the LoginButton in a fragment, you need to set the fragment on the button as shown by calling setFragment.

You then need to call FacebookSdk.initialize to initialize the SDK, and then call CallbackManager.Factory.create to create a callback manager to handle login responses. Here's an example of adding the callback in a fragment:

public class MainActivity extends FragmentActivity {
    CallbackManager callbackManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        LoginButton loginButton = (LoginButton) view.findViewById(R.id.usersettings_fragment_login_button);
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { ... });
    }

Finally you should call callbackManager.onActivityResult to pass the login results to the LoginManager via callbackManager.

Register a Callback

To respond to a login result, you need to register a callback with either LoginManager or LoginButton. If you register the callback with LoginButton, don't need to register the callback on Login manager.

You add the callback to your activity or fragment's onCreate() method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(this.getApplicationContext());

    callbackManager = CallbackManager.Factory.create();

    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    // App code
                }

                @Override
                public void onCancel() {
                     // App code
                }

                @Override
                public void onError(FacebookException exception) {
                     // App code   
                }
    });
}

If login succeeds, the LoginResult parameter has the new AccessToken, and the most recently granted or declined permissions.

You don't need a registerCallback for login to succeed, you can choose to follow current access token changes with the AccessTokenTracker class described below.

Then in onActivityResult() forward the login results to the callbackManager created in onCreate():

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

Every activity and fragment that you integrate with the FacebookSDK Login or Share should forward onActivityResult to the callbackManager.

To learn more about getting additional permissions see:

Managing Permissions, Android, Permissions with Facebook Login



回答3:

I have used facebook sdk 4.10.0 to integrate login in my android app. Tutorial I followed is :

Facebook login integration android studio.

You will be able to get first name, last name, email, gender , facebook id and birth date from facebbok.

Above tutorial also explains how to create app in facebook developer console through video.

Gradle.build

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.demonuts.fblogin"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    repositories {
        mavenCentral()
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.facebook.android:facebook-android-sdk:4.10.0'
    compile 'com.github.androidquery:androidquery:0.26.9'
}

Source code for activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical"
    tools:context="com.demonuts.fblogin.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:layout_marginLeft="10dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/text"/>

    <ImageView
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:id="@+id/ivpic"
        android:src="@mipmap/ic_launcher"/>

    <com.facebook.login.widget.LoginButton
        android:id="@+id/btnfb"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />   </LinearLayout>

Code for MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.androidquery.AQuery;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
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.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {



      private AQuery aQuery;
        private ImageView ivpic;
        private TextView tvdetails;
        private CallbackManager callbackManager;
        private AccessTokenTracker accessTokenTracker;
        private ProfileTracker profileTracker;
        private LoginButton loginButton;
        private FacebookCallback&lt;LoginResult&gt; callback = new FacebookCallback&lt;LoginResult&gt;() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Log.v("LoginActivity", response.toString());

                                // Application code
                                try {
                                    Log.d("tttttt",object.getString("id"));
                                    String birthday="";
                                    if(object.has("birthday")){
                                        birthday = object.getString("birthday"); // 01/31/1980 format
                                    }

                                    String fnm = object.getString("first_name");
                                    String lnm = object.getString("last_name");
                                    String mail = object.getString("email");
                                    String gender = object.getString("gender");
                                    String fid = object.getString("id");
                                    tvdetails.setText("Name: "+fnm+" "+lnm+" \n"+"Email: "+mail+" \n"+"Gender: "+gender+" \n"+"ID: "+fid+" \n"+"Birth Date: "+birthday);
                                    aQuery.id(ivpic).image("https://graph.facebook.com/" + fid + "/picture?type=large");
                                    //https://graph.facebook.com/143990709444026/picture?type=large
                                    Log.d("aswwww","https://graph.facebook.com/"+fid+"/picture?type=large");

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id, first_name, last_name, email, gender, birthday, location");
                request.setParameters(parameters);
                request.executeAsync();

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException error) {

            }
        };


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            FacebookSdk.sdkInitialize(this);
            setContentView(R.layout.activity_main);

            tvdetails = (TextView) findViewById(R.id.text);
            ivpic = (ImageView) findViewById(R.id.ivpic);

            loginButton = (LoginButton) findViewById(R.id.btnfb);
            aQuery = new AQuery(this);

            callbackManager = CallbackManager.Factory.create();

            accessTokenTracker= new AccessTokenTracker() {
                @Override
                protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {

                }
            };

            profileTracker = new ProfileTracker() {
                @Override
                protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {

                }
            };

            accessTokenTracker.startTracking();
            profileTracker.startTracking();
            loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
            loginButton.registerCallback(callbackManager, callback);

        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            callbackManager.onActivityResult(requestCode, resultCode, data);

        }

        @Override
        public void onStop() {
            super.onStop();
            accessTokenTracker.stopTracking();
            profileTracker.stopTracking();
        }

        @Override
        public void onResume() {
            super.onResume();
            Profile profile = Profile.getCurrentProfile();

        }

    }


回答4:

  1. First Go to https://developers.facebook.com/ ,Login and select My Apps and create a App.

  2. Follow the given instruction on by one properly.

  3. Give packagename and packagename.ActivityName, select use App name then save it.

  4. Generate Hash Key (Download OpenSSL) and (Java JDK). - For windows!

  5. Extract the OpenSSL stuffs to C:\OpenSSL

  6. Go to CMD prompt set the current path to JDK's bin folder.

  7. Then use this command :

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Shredder\.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary | "C:\OpenSSL\bin\openssl" base64

Make sure you are using proper Paths like UserAccountName etc.Mine was shredder.After that use Password : 123456.

  1. Paste the hashKey to the required field. Then follow along....

  2. Use the following code if required.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign__in);
        String fb_id ="";
        String fb_fName ="";
        String fb_lName ="";
        String fb_email ="";
        String EMAIL = "email";
    
        CallbackManager callbackManager = CallbackManager.Factory.create();
        final LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setReadPermissions(Arrays.asList(EMAIL));
    
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
    
                String userId = loginResult.getAccessToken().getUserId();
    
                GraphRequest graphRequest = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        getUserFbUserInfo (object);
                    }
                });
    
                Bundle parameters = new Bundle();
                parameters.putString("fields", "first_name,last_name,email,id");
                graphRequest.setParameters(parameters);
                graphRequest.executeAsync();
    
    
                Intent it = new Intent(getApplicationContext(), Home_Page.class);
                it.putExtra("fbLogin", true);
                startActivity(it);
            }
    
            @Override
            public void onCancel() {
                // App code
            }
    
            @Override
            public void onError(FacebookException exception) {
                // App code
            }
        });
    
    
    }
    
    private void getUserFbUserInfo(JSONObject object) {
    
    
            try {
                fb_email = object.getString("email");
                fb_fName = object.getString("first_name");
                fb_lName = object.getString("last_name");
                fb_id = object.getString("id");
            } 
            catch (JSONException e) {
                e.printStackTrace(); 
            }   
    }
    
    @Override
    protected void onActivityResult ( int requestCode, int resultCode, Intent data){
        callbackManager.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }
    

    }



回答5:

Check this simple facebook login Library:

https://github.com/sromku/android-simple-facebook

Here is the link to my uploaded demo for simple facebook login with custom button: http://www.demoadda.com/demo/android/login-with-facebook_108

Its the simplest way to implement the facebook login in android application.

You can add the button like this :

<TextView
            android:id="@+id/btnFb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:background="@null"
            android:gravity="center"
            android:text="Login with Facebook"
            android:textColor="@color/white" />

And in gradle File you can add:

compile 'com.sromku:simple-fb:4.1.1'

Please check.



回答6:

FACEBOOK LOGIN STEPBYSTEP 

   FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        printHashKey();

meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />



btnFacebook.setReadPermissions("public_profile","email");


 btnFacebook.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            String facebook_email;
            String name;
            String profilePicUrl;
            private ProfileTracker mProfileTracker;

            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.e("facabook","Step1");
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Log.e("LoginActivity", response.toString());

                                // Application code
                                try {
                                    facebook_email = object.getString("email");
                                    name=object.getString("name");
                                    if (object.has("picture")) {
                                        profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");
                                        // set profile image to imageview using Picasso or Native methods
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                if(Profile.getCurrentProfile() == null) {
                                    mProfileTracker = new ProfileTracker() {
                                        @Override
                                        protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
                                            // profile2 is the new profile
                                            Log.e("facebook - profile", profile2.getFirstName());

                                            facebookLogin(facebook_email,name,profilePicUrl,Constant.DUMMY_PASSWORD);
                                            mProfileTracker.stopTracking();
                                        }
                                    };
                                    mProfileTracker.startTracking();
                                } else {
                                    facebookLogin(facebook_email,name,profilePicUrl,Constant.DUMMY_PASSWORD);
                                }
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,picture.type(large)");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                Log.e("facebook - onCancel", "cancelled");
            }

            @Override
            public void onError(FacebookException e) {
                Log.e("facebook - onError", e.getMessage());
                Toast.makeText(SignInActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
            }
        });

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.e("Request Code", requestCode + "===========");
        if(requestCode==64206)
        {
            callbackManager.onActivityResult(requestCode, resultCode, data);
        }
    }