简体   繁体   中英

Login with facebook into android app

I want to add login with facebook feature into my android app. How can i do that? Is that right? https://developers.facebook.com/docs/facebook-login/android

STEP ONE

Did you registered your app? If you didn't, go to https://developers.facebook.com/apps/ , click Add a New App in the top right and follow the instructions.

STEP TWO

The 2nd step is add Facebook SDK to your Project . You can do that follow the https://developers.facebook.com/docs/android/getting-started

  • In Android Studio, create a new project with API 15 as minimum SDK

  • The Facebook SDK is available on Maven Central, so edit your build.gradle and add repositories { mavenCentral() } before dependencies

  • Then, add compile 'com.facebook.android:facebook-android-sdk:4.7.0 in dependencies

  • Build your project and initialize the Facebook SDK into your app

The code is the following:

import com.facebook.FacebookSdk;

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

STEP THREE

The Facebook application ID you received when you registered your app should be added to your strings.xml .

<string name="facebook_app_id">123456908761030</string>

The, you have to edit your AndroidManifest.xml adding a INTERNET uses-permission (to be able to connect to Facebook's servers) and a meta-data to the Application element (for the Facebook App ID).

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

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

STEP FOUR

Define FacebookActivity as another Activity in your Manifest. If handles most of the configuration changes itself using configChanges .

<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" />

STEP FIVE

Create/Add the Login Button in your XML layout (wherever you want).

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

STEP SIX

In your Activity, declare the widget you defined in the layout as field of the class.

private LoginButton loginButton;

Declare a CallbackManager as another field to manage the callback used in the app.

private CallbackManager callbackManager;

Initialize your instance of CallbackManager .

callbackManager = CallbackManager.Factory.create();

Initialize the widget using findViewById .

loginButton = (LoginButton) view.findViewById(R.id.usersettings_fragment_login_button);

LAST STEP

Create a callback to handle the results of the login:

  • if the login attempt is successful, onSuccess is called

  • if the user cancels the login attempt, onCancel is called

  • if an error occurs, onError is called

The code is:

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 e) {
        // App code
    }
});

Then, in onActivityResult() :

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

SOME LINKS

Tutorial TutsPlus: LINK

App sample (slidenerd): LINK

Video tutorial (slidenerd): LINK

Get logged user info: LINK

            **Process Login With Facebook**
        **Working on Play Store** 

    **Link 

 - https://play.google.com/store/apps/details?id=com.codecube.airbucks&hl=en

**



            Registered your new app? If you didn't, go to https://developers.facebook.com/apps/, click Add a New App in the top right and follow the instructions. **step by step**

            **Manifest Permission**
            <uses-permission android:name="android.permission.INTERNET" />
                <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
                <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

            **build.Gradle Dependency**
            compile 'com.facebook.android:facebook-android-sdk:4.8.0'  // in airbuck

                /*compile 'com.facebook.android:facebook-android-sdk:[4,5)'*/


             <activity android:name="com.facebook.FacebookActivity"
                        android:theme="@android:style/Theme.Translucent.NoTitleBar"
                        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
                        android:label="@string/app_name" />
                    <meta-data android:name="com.facebook.sdk.ApplicationName"
                        android:value="@string/app_name" />
                    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

                    <provider android:authorities="com.facebook.app.FacebookContentProvider1854328631556764"
                        android:name="com.facebook.FacebookContentProvider"
                        android:exported="true"/> 

        **Layout Xml Code**
        <com.facebook.login.widget.LoginButton
                android:id="@+id/login_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />

        **Put own generate facebook Key in String.xml File** 
        <string name="facebook_app_id">1854328631556764</string>
            <string name="fb_login_protocol_scheme">fb1854328631556764</string>

            **MainActivity CODE**
             protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main1);
                    FacebookSdk.sdkInitialize(this.getApplicationContext());
                    AppEventsLogger.activateApp(this);   

                    callbackManager = CallbackManager.Factory.create();
                    fbloginButton = (LinearLayout) findViewById(R.id.facebook_button);


                    fbloginButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                    int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
                                            android.Manifest.permission.CAMERA);
                                    if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                                        //showing dialog to select image
                                        callFacebook();
                                        Log.e("permission", "granted");
                                    } else {
                                        ActivityCompat.requestPermissions(MainActivity.this,
                                                new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE,
                                                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, 1);
                                    }
                                } else {
                                    callFacebook();
                                }
                        }
                    });
                }

             **CAllOnFAcebook**
                public void callFacebook() {

                    callbackManager = CallbackManager.Factory.create();

            //        LoginManager.getInstance().logInWithReadPermissions(MainActivity2.this, Arrays.asList("email"));

                    LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile"));

                    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

                        @Override
                        public void onSuccess(LoginResult loginResult) {
                            Log.e("keshav","onSuccess called ");
                            GraphRequest request = GraphRequest.newMeRequest(
                                    loginResult.getAccessToken(),
                                    new GraphRequest.GraphJSONObjectCallback() {
                                        @Override
                                        public void onCompleted(
                                                JSONObject object,
                                                GraphResponse response) {
                                            // Application code
                                            Log.v("LoginActivityfacebook", response.toString());

                                            try {
                                                JSONObject data = response.getJSONObject();
                                                facebookName = data.getString("name");
                                                facebookEmail = data.getString("email");
                                                facebookId = data.getString("id");
                                                facebookLink = data.getString("link");
                                                facebookLink = facebookLink.replace("https://www.facebook.com/app_scoped_user_id/", "");
                                                facebookLink = facebookLink.replace("/", "");
                                                Log.e("profilelink", "" + facebookLink);
                                                facebookLink = "https://graph.facebook.com/" + facebookLink + "/picture";

                                                Log.e("facebookName", "is  ->  " + facebookName);
                                                Log.e("facebookEmail", "is  ->  " + facebookEmail);
                                                Log.e("facebookId", "is  ->  " + facebookId);
                                                Log.e("facebookLink", "is  ->  " + facebookLink);


                                                    Log.e("Keshav","Suceesfully Login "+facebookName);



                                                } else {
                                                    CommonMethod.showAlert("Intenet Connectivity Failure", MainActivity.this);
                                                }
                                            } catch (JSONException e) {
                                                // TODO Auto-generated catch block
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                            Bundle parameters = new Bundle();
                            parameters.putString("fields", "id,name,email,gender, birthday,link");
                            request.setParameters(parameters);
                            request.executeAsync();
                        }

                        @Override
                        public void onCancel() {
                            // App code
                            Log.i(TAG, "cancelTriggered");
                        }

                        @Override
                        public void onError(FacebookException exception) {
                            // App code
                            Log.i(TAG, "errorTriggered");
                        }
                    });
                    LoginManager.getInstance().logOut();                //  TODO Add Me Using this previous facebook login id password logout
                }


            **Process Login With Facebook**
        **Working on Play Store** 

    **Link https://play.google.com/store/apps/details?id=com.codecube.airbucks&hl=en**

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM