正确使用facebook登录

时间:2014-05-14 16:18:42

标签: android facebook android-facebook

在我的应用程序的起始页面上,我要求用户通过Facebook进行身份验证,然后我请求一些权限并获取一些信息:

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

我能够获得所有这些信息,但是转到我的下一页我想在列表视图上给出一个按钮,用户可以在那里发布朋友墙。我跟着HelloFacebook示例,它就像一个魅力,但在我的情况下,当我尝试在一个片段中实现它不能按预期工作,我不希望用户每次他想要发布时登录(我使用的是这里的额外许可 - 发布)我必须在这个片段中实现所有生命周期事件吗?有没有其他或推荐的方法?

目前我正在做的是:

我的班级声明:

public class FragmentTab1 extends Fragment {

班级变量:

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;

与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;

    } 

在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());

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

这是我的facebook post方法,我在点击按钮上调用它,这是在列表视图中:

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();
        }
    }

然而,这似乎不是一个正确的方法,有没有更好的方法?另外,如何检测用户会话是否已过期并提示用户再次登录? Docs似乎没有透露Login按钮的内部功能?

2 个答案:

答案 0 :(得分:0)

不要开始新的会话....在源代码中更改它

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

答案 1 :(得分:0)

  • 在项目中添加facebook SDK
  • 在标记下的AndroidManifest.xml中添加以下行  

        <activity android:name="com.facebook.LoginActivity" />
    
  • 还在string.xml中添加facebook app id

  • 声明私人成员

    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();
        }
        }
    

    查看标有“json”的日志猫,你将拥有一个facebook对象