com.facebook.widget.LoginButton Java Examples

The following examples show how to use com.facebook.widget.LoginButton. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FragmentSocialTimelineLayouts.java    From aptoide-client with GNU General Public License v2.0 5 votes vote down vote up
@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        State state;
        if(getArguments()!=null){
            state = State.values()[getArguments().getInt(STATE_ARG, 0)];
        }else{
            state = State.NONE;
        }

        switch (state){
            case LOGGED_IN:
                showFriends(view);
                break;
            case FRIENDS_INVITE:
                showInviteFriends(view);
                break;
            default:
            case LOGOUT_FIRST:
                LoginButton fb_login_button = (LoginButton) view.findViewById(R.id.fb_login_button);
                fb_login_button.setReadPermissions(Arrays.asList("email", "user_friends"));
                fb_login_button.setOnErrorListener(new LoginButton.OnErrorListener() {
                    @Override
                    public void onError(FacebookException error) {
                        error.printStackTrace();
                        Toast.makeText(Aptoide.getContext(), R.string.error_occured, Toast.LENGTH_LONG).show();
                    }
                });
                fb_login_button.setFragment(getParentFragment());
                fb_login_button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        FlurryAgent.logEvent("Social_Timeline_Clicked_On_Login_With_Facebook");
                    }
                });
                break;
        }

    }
 
Example #2
Source File: LoginActivity.java    From aptoide-client with GNU General Public License v2.0 5 votes vote down vote up
private void setUpFacebook(final Bundle savedInstanceState) {
    uiLifecycleHelper = new UiLifecycleHelper(this, statusCallback);
    uiLifecycleHelper.onCreate(savedInstanceState);

    LoginButton fbButton = (LoginButton) findViewById(R.id.fb_login_button);
    fbButton.setReadPermissions(Arrays.asList("email", "user_friends"));
}
 
Example #3
Source File: FacebookFragment.java    From giraff-android with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_dev, container, false);

    LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
    authButton.setFragment(this);

    return view;
}
 
Example #4
Source File: LoginButtonTest.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
@SmallTest
@MediumTest
@LargeTest
public void testCanAddReadPermissions() {
    MockTokenCachingStrategy cache = new MockTokenCachingStrategy(null, 0);
    ScriptedSession session = new ScriptedSession(getActivity(), "SomeId", cache);
    SessionTestsBase.SessionStatusCallbackRecorder statusRecorder = new SessionTestsBase.SessionStatusCallbackRecorder();

    // Verify state with no token in cache
    assertEquals(SessionState.CREATED, session.getState());

    final LoginButton button = new LoginButton(getActivity());
    button.setSession(session);
    button.setReadPermissions("read_permission", "read_another");
    session.addAuthorizeResult("A token of thanks", new ArrayList<String>(), AccessTokenSource.TEST_USER);
    session.addCallback(statusRecorder);

    button.performClick();

    statusRecorder.waitForCall(session, SessionState.OPENING, null);
    statusRecorder.waitForCall(session, SessionState.OPENED, null);

    // Verify token information is cleared.
    session.closeAndClearTokenInformation();
    assertTrue(cache.getSavedState() == null);
    statusRecorder.waitForCall(session, SessionState.CLOSED, null);

    // Wait a bit so we can fail if any unexpected calls arrive on the
    // recorder.
    stall(STRAY_CALLBACK_WAIT_MILLISECONDS);
    statusRecorder.close();
}
 
Example #5
Source File: LoginButtonTest.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
@SmallTest
@MediumTest
@LargeTest
public void testCanAddPublishPermissions() {
    MockTokenCachingStrategy cache = new MockTokenCachingStrategy(null, 0);
    ScriptedSession session = new ScriptedSession(getActivity(), "SomeId", cache);
    SessionTestsBase.SessionStatusCallbackRecorder statusRecorder =
            new SessionTestsBase.SessionStatusCallbackRecorder();

    // Verify state with no token in cache
    assertEquals(SessionState.CREATED, session.getState());

    final LoginButton button = new LoginButton(getActivity());
    button.setSession(session);
    button.setPublishPermissions("publish_permission", "publish_another");
    session.addAuthorizeResult("A token of thanks", new ArrayList<String>(), AccessTokenSource.TEST_USER);
    session.addCallback(statusRecorder);

    button.performClick();

    statusRecorder.waitForCall(session, SessionState.OPENING, null);
    statusRecorder.waitForCall(session, SessionState.OPENED, null);

    // Verify token information is cleared.
    session.closeAndClearTokenInformation();
    assertTrue(cache.getSavedState() == null);
    statusRecorder.waitForCall(session, SessionState.CLOSED, null);

    // Wait a bit so we can fail if any unexpected calls arrive on the
    // recorder.
    stall(STRAY_CALLBACK_WAIT_MILLISECONDS);
    statusRecorder.close();
}
 
Example #6
Source File: LoginButtonTest.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
@SmallTest
@MediumTest
@LargeTest
public void testCantAddReadThenPublishPermissions() {
    final LoginButton button = new LoginButton(getActivity());
    button.setReadPermissions("read_permission", "read_another");
    try {
        button.setPublishPermissions("read_permission", "read_a_third");
        fail("Should not be able to reach here");
    } catch (Exception e) {
        assertTrue(e instanceof UnsupportedOperationException);
    }
}
 
Example #7
Source File: LoginButtonTest.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
@SmallTest
@MediumTest
@LargeTest
public void testCantAddPublishThenReadPermissions() {
    final LoginButton button = new LoginButton(getActivity());
    button.setPublishPermissions("publish_permission", "publish_another");
    try {
        button.setReadPermissions("publish_permission", "publish_a_third");
        fail("Should not be able to reach here");
    } catch (Exception e) {
        assertTrue(e instanceof UnsupportedOperationException);
    }
}
 
Example #8
Source File: LoginButtonTest.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
@SmallTest
@MediumTest
@LargeTest
public void testCanAddReadThenPublishPermissionsWithClear() {
    final LoginButton button = new LoginButton(getActivity());
    button.setReadPermissions("read_permission", "read_another");
    button.clearPermissions();
    button.setPublishPermissions("publish_permission", "publish_another");
}
 
Example #9
Source File: LoginButtonTest.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
@SmallTest
@MediumTest
@LargeTest
public void testCanSetDefaultAudience() {
    SessionTestsBase.MockTokenCachingStrategy cache = new SessionTestsBase.MockTokenCachingStrategy(null, 0);
    ScriptedSession session = new ScriptedSession(getActivity(), "SomeId", cache);
    SessionTestsBase.SessionStatusCallbackRecorder statusRecorder =
            new SessionTestsBase.SessionStatusCallbackRecorder();

    // Verify state with no token in cache
    assertEquals(SessionState.CREATED, session.getState());

    final LoginButton button = new LoginButton(getActivity());
    button.setSession(session);
    button.setPublishPermissions("publish_permission", "publish_another");
    button.setDefaultAudience(SessionDefaultAudience.FRIENDS);
    session.addAuthorizeResult("A token of thanks", new ArrayList<String>(), AccessTokenSource.TEST_USER);
    session.addCallback(statusRecorder);

    button.performClick();

    statusRecorder.waitForCall(session, SessionState.OPENING, null);
    statusRecorder.waitForCall(session, SessionState.OPENED, null);

    assertNotNull(session.getLastRequest());
    assertEquals(SessionDefaultAudience.FRIENDS, session.getLastRequestAudience());

    // Verify token information is cleared.
    session.closeAndClearTokenInformation();
    assertTrue(cache.getSavedState() == null);
    statusRecorder.waitForCall(session, SessionState.CLOSED, null);

    // Wait a bit so we can fail if any unexpected calls arrive on the
    // recorder.
    stall(STRAY_CALLBACK_WAIT_MILLISECONDS);
    statusRecorder.close();
}
 
Example #10
Source File: MyNewsfeedFragment.java    From FacebookNewsfeedSample-Android with Apache License 2.0 5 votes vote down vote up
/**
 * A method which initializes all of our members pointing to layout {@link android.view.View View}s.
 * @param viewGroup  The {@link android.view.ViewGroup ViewGroup} representing this {@link android.support.v4.app.Fragment Fragment}'s screen.
 */
private void initUIConfig(ViewGroup viewGroup) {
   mUsername = (TextView)viewGroup.findViewById(R.id.myNewsFeedFragment_userName);
   mUserProfilePicture = (ProfilePictureView) viewGroup.findViewById(R.id.com_dhsoftware_android_myNewsfeedFragment_userProfilePicture);
   mUserLoginButton = (LoginButton) viewGroup.findViewById(R.id.com_dhsoftware_android_myNewsFeedFragment_userLoginButton);
   // we need this permission to access the user's Newsfeed
   mUserLoginButton.setReadPermissions(Arrays.asList("read_stream"));
   mUserNewsfeed = (PullToRefreshListView) viewGroup.findViewById(R.id.myNewsfeedFragment_userNewsfeed);
   mUserNewsfeed.setAdapter(mAdapter);
   mUserNewsfeed.setOnRefreshListener(mRefreshListener);
}
 
Example #11
Source File: LoginFragment.java    From Klyph with MIT License 4 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
	View view = inflater.inflate(R.layout.fragment_login, container, false);

	authButton = (LoginButton) view.findViewById(R.id.authButton);
	progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
	TextView tv = (TextView) view.findViewById(R.id.app_name_textview);
	tv.setText(KlyphFlags.IS_PRO_VERSION == true ? R.string.app_pro_large_name : R.string.app_large_name);
	
	TextView version = (TextView) view.findViewById(R.id.version);
	version.setText(getString(R.string.about_version, ApplicationUtil.getAppVersion(getActivity())));

	authButton.setReadPermissions(Arrays.asList("read_stream", "friends_about_me", "friends_work_history", "friends_activities",
			"friends_birthday", "user_checkins", "friends_checkins", "user_education_history", "friends_education_history", "user_events",
			"friends_events", "user_groups", "friends_groups", "user_hometown", "friends_hometown", "user_interests", "friends_interests",
			"user_likes", "friends_likes", "user_notes", "friends_notes", "user_online_presence", "friends_online_presence", "user_interests",
			"friends_interests", "user_likes", "friends_likes", "user_notes", "friends_notes", "user_online_presence", "friends_online_presence",
			"user_religion_politics", "friends_religion_politics", "user_status", "friends_status", "user_subscriptions",
			"friends_subscriptions", "user_videos", "friends_videos", "user_website", "friends_website", "user_work_history",
			"friends_work_history", "read_friendlists", "read_mailbox", "read_requests", "read_stream", "xmpp_login", "email", "user_location",
			"user_photos", "friends_photos"));

	authButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {

		@Override
		public void onUserInfoFetched(GraphUser user)
		{
			Log.d("LoginFragment", "onUserInfoFetched ");
			if (Session.getActiveSession().isOpened() && user != null)
			{
				Log.d("LoginFragment", "onUserInfoFetched2 ");
				
				
				User u = new User();
				u.setUid(user.getId());
				u.setName(user.getName());
				u.setFirst_name(user.getFirstName());
				u.setMiddle_name(user.getMiddleName());
				u.setLast_name(user.getLastName());
				u.setBirthday(user.getBirthday());
				u.setEmail((String) user.getProperty("email"));
				u.setSex((String) user.getProperty("gender"));
				// u.setIn((String)
				// user.getProperty("interested_in"));
				u.setLocale((String) user.getProperty("locale"));
				u.setRelationship_status((String) user.getProperty("relationship_status"));
				u.setUsername((String) user.getProperty("username"));

				try
				{
					u.setTimezone(((Double) user.getProperty("timezone")).intValue());
				}
				catch (Exception e)
				{}
				
				KlyphSession.setSessionUser(u);

				if (getActivity() != null)
				{
					((LoginFragmentCallBack) getActivity()).onUserInfoFetched(u);
				}
			}
		}
	});

	authButton.setFragment(this);

	return view;
}
 
Example #12
Source File: LoginActivity.java    From flow-android with MIT License 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.login_layout);

    databaseLoader = new FlowDatabaseLoader(this.getApplicationContext(), getHelper());

    mLoginProgressBar = (ProgressBar) findViewById(R.id.login_progress_bar);
    mLoginButton = (LoginButton) findViewById(R.id.login_button);
    mSkipLoginButton = (Button) findViewById(R.id.skip_login_button);

    // The only way to get to the login screen is if you're logged out.
    ((FlowApplication) getApplication()).setUserLoggedIn(false);

    mLoginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
        @Override
        public void onUserInfoFetched(GraphUser user) {
            if (user != null) {
                if (FlowAsyncClient.getSessionCookie() == null ||
                        StringUtils.isEmpty(FlowAsyncClient.getCsrfToken())) {
                    // Clear existing cookies to force a login, in case we're missing a CSRF token
                    FlowAsyncClient.clearCookie();
                    FlowApiRequests.login(user.getId(), Session.getActiveSession().getAccessToken(),
                            new FlowApiRequestCallbackAdapter() {
                                @Override
                                public void onSuccess(JSONObject response) {
                                    loadDataAndLogin(response);
                                }

                                @Override
                                public void onFailure(String error) {
                                    // Clear Facebook session
                                    if (Session.getActiveSession() != null) {
                                        Session.getActiveSession().closeAndClearTokenInformation();
                                    }
                                    Session.setActiveSession(null);

                                    // Remove any cookies
                                    FlowAsyncClient.clearCookie();

                                    FlowApplication app = (FlowApplication) getApplication();

                                    // TODO(david): The server should return an app error code to be less brittle
                                    if (error.toLowerCase().contains("create an account")) {
                                        app.track("Login with new account");

                                        // Prompt the user to create an account on uwflow.com or skip login
                                        promptCreateAccount();
                                    } else {
                                        JSONObject properties = new JSONObject();
                                        try {
                                            properties.put("error", error);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        app.track("Login error", properties);

                                        // Toast with error text
                                        Toast.makeText(
                                                getApplicationContext(),
                                                "Oops! Couldn't log into Flow. " + error,
                                                Toast.LENGTH_LONG)
                                                .show();
                                        Log.e(TAG, "Error logging in: " + error);

                                        Crashlytics.log(Log.ERROR, TAG, "Error logging in: " + error);
                                    }
                                }
                            });
                }
            }
        }
    });

    Button skipLoginButton = (Button) findViewById(R.id.skip_login_button);
    skipLoginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            skipLogin();
        }
    });

    // TODO(david): Also ensure session cookie hasn't expired
    if (FlowAsyncClient.getSessionCookie() != null) {
        loadDataAndLogin(null);
    }
}
 
Example #13
Source File: LoginButtonTest.java    From FacebookImageShareIntent with MIT License 4 votes vote down vote up
@SmallTest
@MediumTest
@LargeTest
public void testLoginButton() throws Throwable {
    MockTokenCachingStrategy cache = new MockTokenCachingStrategy(null, 0);
    final ScriptedSession session = new ScriptedSession(getActivity(), "SomeId", cache);
    SessionTestsBase.SessionStatusCallbackRecorder statusRecorder = new SessionTestsBase.SessionStatusCallbackRecorder();

    session.addAuthorizeResult("A token of thanks", new ArrayList<String>(), AccessTokenSource.TEST_USER);
    session.addCallback(statusRecorder);

    // Verify state with no token in cache
    Assert.assertEquals(SessionState.CREATED, session.getState());

    // Add another status recorder to ensure that the callback we hand to LoginButton
    // also gets called as expected. We expect to get the same order of calls as statusRecorder does.
    final SessionStatusCallbackRecorder loginButtonStatusRecorder = new SessionStatusCallbackRecorder();

    // Create the button. To get session status updates, we need to actually attach the
    // button to a window, which must be done on the UI thread.
    final LoginButton button = new LoginButton(getActivity());
    runAndBlockOnUiThread(0, new Runnable() {
        @Override
        public void run() {
            getActivity().setContentView(button);
            button.setSession(session);
            button.setSessionStatusCallback(loginButtonStatusRecorder);
            button.performClick();
        }
    });

    statusRecorder.waitForCall(session, SessionState.OPENING, null);
    loginButtonStatusRecorder.waitForCall(session, SessionState.OPENING, null);

    statusRecorder.waitForCall(session, SessionState.OPENED, null);
    loginButtonStatusRecorder.waitForCall(session, SessionState.OPENED, null);

    // Verify token information is cleared.
    session.closeAndClearTokenInformation();
    assertTrue(cache.getSavedState() == null);
    statusRecorder.waitForCall(session, SessionState.CLOSED, null);
    loginButtonStatusRecorder.waitForCall(session, SessionState.CLOSED, null);

    // Wait a bit so we can fail if any unexpected calls arrive on the
    // recorder.
    stall(STRAY_CALLBACK_WAIT_MILLISECONDS);
    statusRecorder.close();
}
 
Example #14
Source File: LoginButtonTest.java    From FacebookImageShareIntent with MIT License 4 votes vote down vote up
@SmallTest
@MediumTest
@LargeTest
// Tests that the onErrorListener gets called if there's an error
public void testLoginFail() {
    MockTokenCachingStrategy cache = new MockTokenCachingStrategy(null, 0);
    ScriptedSession session = new ScriptedSession(getActivity(), "SomeId", cache);
    final Exception openException = new Exception("Open failed!");
    final AtomicBoolean clicked = new AtomicBoolean(false);

    // Verify state with no token in cache
    assertEquals(SessionState.CREATED, session.getState());

    final LoginButton button = new LoginButton(getActivity());
    LoginButton.OnErrorListener listener = new LoginButton.OnErrorListener() {
        @Override
        public void onError(FacebookException exception) {
            synchronized (this) {
                assertEquals(exception.getCause().getMessage(), openException.getMessage());
                clicked.set(true);
                this.notifyAll();
            }
        }
    };
    button.setOnErrorListener(listener);
    button.setSession(session);
    session.addAuthorizeResult(openException);

    button.onAttachedToWindow();
    button.performClick();

    try {
        synchronized (listener) {
            listener.wait(DEFAULT_TIMEOUT_MILLISECONDS);
        }
    } catch (InterruptedException e) {
        fail("Interrupted during open");
    }

    if (!clicked.get()) {
        fail("Did not get exception");
    }
}
 
Example #15
Source File: LoginButtonTest.java    From FacebookImageShareIntent with MIT License 4 votes vote down vote up
@SmallTest
@MediumTest
@LargeTest
public void testCantAddMorePermissionsToOpenSession() {
    MockTokenCachingStrategy cache = new MockTokenCachingStrategy(null, 0);
    ScriptedSession session = new ScriptedSession(getActivity(), "SomeId", cache);
    SessionTestsBase.SessionStatusCallbackRecorder statusRecorder =
            new SessionTestsBase.SessionStatusCallbackRecorder();

    // Verify state with no token in cache
    assertEquals(SessionState.CREATED, session.getState());

    final LoginButton button = new LoginButton(getActivity());
    button.setSession(session);
    session.addAuthorizeResult("A token of thanks",
            Arrays.asList(new String[] {"read_permission", "read_another"}), AccessTokenSource.TEST_USER);
    session.addCallback(statusRecorder);

    button.performClick();

    statusRecorder.waitForCall(session, SessionState.OPENING, null);
    statusRecorder.waitForCall(session, SessionState.OPENED, null);

    // this should be fine
    button.setReadPermissions("read_permission", "read_another");

    button.setReadPermissions("read_permission", "read_a_third");
    List<String> permissions = button.getPermissions();
    assertTrue(permissions.contains("read_permission"));
    assertTrue(permissions.contains("read_another"));
    assertFalse(permissions.contains("read_a_third"));

    // Verify token information is cleared.
    session.closeAndClearTokenInformation();
    assertTrue(cache.getSavedState() == null);
    statusRecorder.waitForCall(session, SessionState.CLOSED, null);

    // Wait a bit so we can fail if any unexpected calls arrive on the
    // recorder.
    stall(STRAY_CALLBACK_WAIT_MILLISECONDS);
    statusRecorder.close();
}
 
Example #16
Source File: LoginFragment.java    From KlyphMessenger with MIT License 4 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
	View view = inflater.inflate(R.layout.fragment_login, container, false);

	authButton = (LoginButton) view.findViewById(R.id.authButton);
	progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
	TextView tv = (TextView) view.findViewById(R.id.app_name_textview);
	tv.setText(KlyphFlags.IS_PRO_VERSION == true ? R.string.app_pro_large_name : R.string.app_large_name);

	authButton.setReadPermissions(Arrays.asList(
	"user_online_presence", "friends_online_presence", "read_mailbox", "xmpp_login", "email", "user_friends", "user_photos", "friends_photos"));

	authButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {

		@Override
		public void onUserInfoFetched(GraphUser user)
		{
			if (Session.getActiveSession().isOpened() && user != null)
			{

				User u = new User();
				u.setUid(user.getId());
				u.setName(user.getName());
				u.setFirst_name(user.getFirstName());
				u.setMiddle_name(user.getMiddleName());
				u.setLast_name(user.getLastName());
				u.setBirthday(user.getBirthday());
				u.setEmail((String) user.getProperty("email"));
				u.setSex((String) user.getProperty("gender"));
				// u.setIn((String)
				// user.getProperty("interested_in"));
				u.setLocale((String) user.getProperty("locale"));
				u.setRelationship_status((String) user.getProperty("relationship_status"));
				u.setUsername((String) user.getProperty("username"));

				try
				{
					u.setTimezone(((Double) user.getProperty("timezone")).intValue());
				}
				catch (Exception e)
				{}

				KlyphSession.setSessionUser(u);

				if (getActivity() != null)
				{
					((LoginFragmentCallBack) getActivity()).onUserInfoFetched(u);
				}
			}
		}
	});

	authButton.setFragment(this);

	return view;
}