Using facebook login correctly

2020-06-22 06:08发布

In my application on the start page I ask the user to authenticate via Facebook, then I request for some permissions and fetch some information:

LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
        authButton.setFragment(this);
        authButton.setReadPermissions(Arrays.asList("user_likes", "user_status"));
        fb = new FacebookMain(); 

I am able to get all this information, but moving to my next page I want to give a button on my listview and from there a user can post on a friends wall. I followed the HelloFacebook sample and it works like a charm, however in my case when I try to implement it in a fragment it does not work as intended, I dont want the user to login every time he wants to post (I am using an additional permission here -- to post) DO I have to implement all the lifecycly events here, in this fragment? Is there any other or recommended approach to this?

Currently what I am doing is:

my class declaration:

public class FragmentTab1 extends Fragment {

Class level variables:

String FACEBOOK_ID;
String IMAGE_CONTENT;
EditText SEARCH; 
private static final String PERMISSION = "publish_actions";
Session session;
private final String PENDING_ACTION_BUNDLE_KEY = "com.exa.digitalrem:PendingAction";
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user1;
private UiLifecycleHelper uiHelper;

Functions related to facebook:

private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user1;

private enum PendingAction {
    NONE, POST_PHOTO, POST_STATUS_UPDATE
}



private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state,
            Exception exception) {
        onSessionStateChange(session, state, exception);
    }
}; 

public static boolean isActive() {
    Session session = Session.getActiveSession();
    if (session == null) {
        return false;
    }
    return session.isOpened();
}


private void onSessionStateChange(Session session, SessionState state,
            Exception exception) {
        if (pendingAction != PendingAction.NONE && (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
            new AlertDialog.Builder(getActivity()) .setTitle("cancelled").setMessage("NotGranted").setPositiveButton("Ok", null).show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
        updateUI();
    }

    private void updateUI() {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());



        if (enableButtons && user1 != null) {
            //  profilePictureView.setProfileId(user.getId());
            //  greeting.setText(getString(R.string.app_name, user.getFirstName()));
        } else {
            //  profilePictureView.setProfileId(null);
            //  greeting.setText(null);
        }
    }

    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but
        // we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

    } 

In the onCreate:

 uiHelper = new UiLifecycleHelper(getActivity(), callback);
 uiHelper.onCreate(savedInstanceState);


    if (savedInstanceState != null) {
            name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
            pendingAction = PendingAction.valueOf(name);
        }

        //===============================================

        Session.openActiveSessionFromCache(getActivity());

        //================================================

This is my facebook post method, I call this on a button click, which is in a listview:

public void postFB(String id) {
        System.out.println("in fb");
        if (isNetworkConnected()) {
            Session session = Session.getActiveSession();
            if (session != null) {
                System.out.println("session not null");
                if (hasPublishPermission()) {
                    //do something

                    WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
                            getActivity(), Session.openActiveSessionFromCache(getActivity()),
                            params)).setOnCompleteListener(
                                    new OnCompleteListener() {

                                        @Override
                                        public void onComplete(Bundle values,
                                                FacebookException error) {
                                            // frag3.setFbId(null);
                                            // ---------------------------- got to put
                                            // check here
                                            //  onBackPressed();

                                        }
                                    }).build();
                    feedDialog.show();
                } else if (session.isOpened()) {
                    // We need to get new permissions, then complete the action
                    // when we get called back.

                    session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                            getActivity(), PERMISSION));
                    // do something

                    WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
                            getActivity(), Session.getActiveSession(),
                            params)).setOnCompleteListener(
                                    new OnCompleteListener() {

                                        @Override
                                        public void onComplete(Bundle values,
                                                FacebookException error) {
                                            // frag3.setFbId(null);
                                            // ---------------------------- got to put
                                            // check here
                                            //onBackPressed();

                                        }
                                    }).build();
                    feedDialog.show();
                }
            }else if(session == null){
                System.out.println("login");
            }
        } else {
            Toast.makeText(getActivity(),
                    "Please check your internet connection", Toast.LENGTH_LONG)
                    .show();
        }
    }

This however does not seem to me a correct approach, is there any better way? Also how do I detect if the user session is expired and prompt the user to login again? The Docs dont seem to reveal the internal functioning of the Login button?

2条回答
疯言疯语
2楼-- · 2020-06-22 07:00

Do not start a new session .... change it in the source code

private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state,
        Exception exception) {
    onSessionStateChange(session, state, exception);
}
};
查看更多
冷血范
3楼-- · 2020-06-22 07:02
  • Add the facebook SDK in your project
  • Add below lines in AndroidManifest.xml under tag

        <activity android:name="com.facebook.LoginActivity" />
    
  • Also Add facebook app id in string.xml

  • Declare the private members

    private boolean isOnCreate;
    private List<String> permissions = new ArrayList<String>();
    private JSONObject facebookObject;
    private ProgressDialog progressDialog;
    
    /** The callback. */
    private final com.facebook.Session.StatusCallback callback = new 
    
    com.facebook.Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
    SignInActivity.this.onSessionStateChange(session, state, exception);
    }
    };
    
    private void onSessionStateChange(Session session, SessionState state, Exception         exception) {
    
    if (state == SessionState.OPENED) {
    if (this.isOnCreate) {
     this.isOnCreate = false;
     return;
         }
         onFacebookLoginDone();
    } else if (state == SessionState.CLOSED_LOGIN_FAILED) {
    showErrorMessage();
    }
    }
    
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Session session = Session.getActiveSession();
        if (session == null) {
            session = new Session(this);
            session.closeAndClearTokenInformation();
        }
        Session.setActiveSession(session);
        }
    
        @Override
        public void onClick(View v) {
        switch (v.getId()) {
    
        case R.id.btn_fb_login:
            this.loginUsingFacebook();
            break;
    
        default:
            break;
        }
    
        }
    
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
        }
    
        /**
         * Login using facebook.
         */
        private void loginUsingFacebook() {
        isOnCreate = false;
        final Session session = Session.getActiveSession();
        if (session != null && session.getState().equals(SessionState.OPENED)) {
            Session.openActiveSession(this, true, this.callback);
            onFacebookLoginDone();
        } else {
            final Session.OpenRequest temp = new Session.OpenRequest(this);
            this.permissions.clear();
            this.permissions.add(UserClass.EMAIL);
            this.permissions.add("user_location");
            temp.setPermissions(this.permissions);
            temp.setCallback(this.callback);
            session.openForRead(temp);
        }
    
        }
    
        /**
         * On facebook login done.
         */
        private void onFacebookLoginDone() {
    
        final Bundle bundle = new Bundle();
        bundle.putString("fields", "first_name,last_name,id,location,locale,username,email,verified");
        new PerformSignUpOnServer("/me", bundle).execute();
        }
    
        /**
         * The Class PerformSignUpOnServer.
         */
        private class PerformSignUpOnServer extends AsyncTask<Void, Void, Void> {
    
        /** The server url. */
        private String serverURL;
    
        /** The server bundle. */
        private Bundle serverBundle;
    
        /**
         * Instantiates a new perform sign up on server.
         * 
         * @param url
         *            the url
         * @param bundle
         *            the bundle
         */
        public PerformSignUpOnServer(String url, Bundle bundle) {
    
            this.serverBundle = bundle;
            this.serverURL = url;
        }
    
        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(SignInActivity.this, "", "Loading...");
            super.onPreExecute();
        }
    
        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected Void doInBackground(Void... params) {
    
            signUpUserOnServer(this.serverURL, this.serverBundle);
    
            return null;
    
        }
    
        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Void result) {
    
    
        }
        }
    
        /**
         * Sign up user on server.
         * 
         * @param url
         *            the url
         * @param bundle
         *            the bundle
         */
        private void signUpUserOnServer(String url, Bundle bundle) {
        final Session session = Session.getActiveSession();
        if (session != null && session.isClosed() == false) {
            final Request userInformation = new Request(session, url, bundle, HttpMethod.GET);
            final Response response = userInformation.executeAndWait();
            facebookObject = response.getGraphObject().getInnerJSONObject();
            Log.d("json", facebookObject.toString());
        }
        }
    
        /**
         * On session state change.
         * 
         * @param state
         *            the state
         */
        private void onSessionStateChange(SessionState state) {
    
        if (state == SessionState.OPENED) {
            if (isOnCreate) {
            isOnCreate = false;
            return;
            }
            onFacebookLoginDone();
        }
        }
    

    See your log cat with tag "json" you will have a facebook object

查看更多
登录 后发表回答