티스토리 뷰

액티비티로 페이스북 로그인 구현하기

java :

public class FacebookLoginActivity extends Activity {

    private final String TAG = "FacebookLoginLog";
    private CallbackManager mCallbackManager;    

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

        mCallbackManager = CallbackManager.Factory.create();
        facebookAuth();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onActivityResult(int reqCode, int resCode, Intent data) {
        super.onActivityResult(reqCode, resCode, data);

        mCallbackManager.onActivityResult(reqCode, resCode, data);
    }

    private void facebookAuth() 
    {
        LoginManager.getInstance().logInWithReadPermissions(this,
                Arrays.asList("public_profile", "email")); //user_photos
        LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(final LoginResult result) {
                getUserProfile(result);
            }

            @Override
            public void onError(FacebookException error) {
                Log.d(TAG, "Error: " + error);                
            }

            @Override
            public void onCancel() {
                Log.d(TAG, "onCancel");                
            }
        });
    }

    private void getUserProfile(LoginResult loginResult) {

        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                (object, response) -> {
                    try {
                        String name = object.getString("name");
                        String email = object.getString("email");
                        String photoURL = object.getJSONObject("picture").getJSONObject("data").getString("url");
                        Log.d(TAG, response.toString());

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

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id, name, email, picture.type(normal)");
        request.setParameters(parameters);
        request.executeAsync();
    }         
}

출처
https://developers.facebook.com/docs/facebook-login/android/?locale=ko_KR
https://developers.facebook.com/docs/android/graph?locale=ko_KR

댓글