android - 使用共享首选项/ session 使用 Facebook-Android-SDK 3.0 登录

标签 android session authentication sharedpreferences facebook-android-sdk

很长一段时间以来,我使用的登录名几乎与 this tutorial 中的登录名相同。直到我意识到它已被弃用。

因此,作为一名优秀的开发人员,我决定尝试将我的登录升级到 Facebook Android 3.0 SDK,但当我查看文档时,我不禁想知道为什么 Facebook 会在旧版本运行良好时过度复杂化他们的登录。

我当前的代码如下,但我有点困惑。我过去只是简单地向 Facebook 发出授权请求,从他们那里获取一些信息,将其与我的数据库进行比较,如果它与 id 匹配,则将一些信息保存到共享首选项并打开我的应用程序的主页 Activity 。但是,对于 3.0 和“ session ”,我有点困惑:

  1. 我必须在我的所有 Activity 中使用这些“类(class)”吗?
  2. 如果是这样,它们是否会在我的整个应用程序中持续存在?
  3. 如果我们已经有了共享偏好, session 还有什么意义?

代码:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphUser;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class FBLoginActivity extends Activity {
    private static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token=";

    private TextView textInstructionsOrLink;
    private Button buttonLoginLogout;
    private Session.StatusCallback statusCallback = new SessionStatusCallback();
 // List of additional write permissions being requested
    private static final List<String> PERMISSIONS = Arrays.asList("email","user_about_me","user_activities",
    "user_birthday","user_education_history", "user_events","user_hometown", "user_groups","user_interests","user_likes",
    "user_location","user_photos","user_work_history");

    SharedPrefs sharedprefs;
    // Request code for reauthorization requests.
    private static final int REAUTH_ACTIVITY_CODE = 100;

    // Flag to represent if we are waiting for extended permissions
    private boolean pendingAnnounce = false;
    protected String college; 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.facebooklogin); 
        buttonLoginLogout = (Button)findViewById(R.id.buttonLoginLogout);
        textInstructionsOrLink = (TextView)findViewById(R.id.instructionsOrLink);

        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

        Session session = Session.getActiveSession();
        if (session == null) {
            if (savedInstanceState != null) {
                session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            }
            if (session == null) {
                session = new Session(this);
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(PERMISSIONS));
            }
        }

        updateView();
    }

    @Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    public void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

    private void updateView() {
        Session session = Session.getActiveSession();
        if (session.isOpened()) {
            Log.i("permissions",session.getPermissions().toString());
            //makeLikesRequest(session);
            makeMeRequest(session);

            Log.i("token",session.getAccessToken());
            Log.i("token experation", session.getExpirationDate().toString());




            Intent i = new Intent(getApplicationContext(), FaceTestActivity.class);
            startActivity(i);
            /*buttonLoginLogout.setText(R.string.logout);
            buttonLoginLogout.setOnClickListener(new OnClickListener() {
                public void onClick(View view) { onClickLogout(); }
            });*/
        } else {
            textInstructionsOrLink.setText(R.string.instructions);
            buttonLoginLogout.setText(R.string.login);
            buttonLoginLogout.setOnClickListener(new OnClickListener() {
                public void onClick(View view) { onClickLogin(); }
            });
        }
    }

    private void onClickLogin() {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(PERMISSIONS));
        } else {

            Session.openActiveSession(this, true, statusCallback);
        }

    }

    private void onClickLogout() {
        Session session = Session.getActiveSession();
        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();
        }
    }

    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            updateView();
        }
    }

   /* private void makeLikesRequest(final Session session) {
        Request.Callback callback = new Request.Callback() {

            @Override
            public void onCompleted(Response response) {
                // response should have the likes

                 // If the response is successful
                if (session == Session.getActiveSession()) {

                    Log.i("likes response", response.toString());
                }

            }
        };
        Request request = new Request(session, "me/likes", null, HttpMethod.GET, callback);
        RequestAsyncTask task = new RequestAsyncTask(request);
        task.execute();
    } */


    private void makeMeRequest(final Session session) {
        // Make an API call to get user data and define a 
        // new callback to handle the response.
        Request request = Request.newMeRequest(session, 
                new Request.GraphUserCallback() {
            @Override
            public void onCompleted(GraphUser user, Response response) {
                // If the response is successful
                if (session == Session.getActiveSession()) {
                    if (user != null) {
                        // Set the id for the ProfilePictureView
                        // view that in turn displays the profile picture.
                        Log.i("user", user.toString());
                        JSONObject json = user.getInnerJSONObject();
                        Log.i("json me response", json.toString());

                        RequestParams params = new RequestParams();

                        String fb_token = session.getAccessToken().toString();
                        String fb_token_expires = session.getExpirationDate().toString();
                        Log.i("fb_token", fb_token);
                        params.put("fb_token",fb_token);
                        Log.i("fb_token_expires", fb_token_expires);
                        params.put("fb_token_expires",fb_token);



                        if(user.getBirthday() != null){
                            String birthday = user.getBirthday();
                            Log.i("birthday_1",birthday);
                            params.put("birthday", birthday);
                        }

                        if(user.getFirstName() != null){
                            String firstName = user.getFirstName();
                            Log.i("first name_2", firstName);
                            params.put("firstName", firstName);
                        }

                        if(user.getLastName() != null){
                            String lastName = user.getLastName();
                            Log.i("last name_3", lastName);
                            params.put("lastName", lastName);
                        }

                        if(user.getLink() != null){
                            String fb_link = user.getLink();
                            Log.i("fb_link_4", fb_link);
                            params.put("fb_link", fb_link);
                        }

                        if(user.getId() != null){
                            String fb_uid = user.getId();
                            Log.i("fb uid_5", fb_uid);
                            params.put("fb_uid", fb_uid);
                        }


                        if(user.getProperty("gender") != null){
                            String gender = user.getProperty("gender").toString();
                            Log.i("gender_6", gender);
                            params.put("gender", gender);
                        }

                        if(user.getProperty("email") != null){
                            String email = user.getProperty("email").toString();
                            Log.i("email_7", email);
                            params.put("email", email);
                        }


                        if(user.getProperty("verified") != null){
                            String verified = user.getProperty("verified").toString();
                            Log.i("verified_8", verified);
                            params.put("verified", verified);

                        }


                        if(user.getProperty("bio") != null){
                            String bio = user.getProperty("bio").toString();
                            Log.i("bio_9", bio);
                            params.put("bio", bio);

                        }
                        if(user.getLocation().getProperty("name") != null){

                            String location = user.getLocation().getProperty("name").toString();
                            Log.i("location_10", location);
                            params.put("location", location);

                        } 


                        //user Location
                        JSONArray education_array = (JSONArray)user.getProperty("education");
                        if (education_array.length() > 0) {
                            String education_length= String.valueOf(education_array.length());
                            Log.i("education_length",education_length);
                            ArrayList<String> collegeNames = new ArrayList<String> ();
                            for (int i=0; i < education_array.length(); i++) {
                                JSONObject edu_obj = education_array.optJSONObject(i);


                                // Add the language name to a list. Use JSON
                                // methods to get access to the name field.

                              String type = edu_obj.optString("type");
                              Log.i("type of edu", type);
                              if(type.equalsIgnoreCase("college")){
                                  JSONObject school_obj = edu_obj.optJSONObject("school");
                                  college = school_obj.optString("name");
                                  //Log.i("college",college);



                              }


                            }  
                            params.put("college", college);
                            Log.i("college", college);

                        }


                        RestClient.post(FB_LOGIN_URL, params, new JsonHttpResponseHandler() {
                            @Override
                            public void onFailure(Throwable arg0, JSONObject arg1) {
                                // TODO Auto-generated method stub
                                super.onFailure(arg0, arg1);

                                Log.i("FAILED TO LOGIN:", arg1.toString());
                                Toast.makeText(getApplicationContext(), arg1.toString() , Toast.LENGTH_LONG).show();
                            }

                            @Override
                            public void onSuccess(JSONObject json) {

                                Log.i("Login Request Success:", json.toString());

                                try {

                                    sharedprefs.createLoginSession(json);
                                    HashMap<String, String> user = sharedprefs.getUserDetails();
                                    String profile_uid = user.get(sharedprefs.KEY_UID);
                                    Intent i = new Intent(getApplicationContext(), TabHostFragmentActivity.class);
                                    i.putExtra("profile_uid", profile_uid);
                                    startActivity(i);
                                    finish();


                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                            }
                        });










                    }
                }
                if (response.getError() != null) {
                    // Handle errors, will do so later.
                }
            }
        });
        request.executeAsync();
    } 
}

最佳答案

您必须始终引用唯一的 Session 类。 每个 Activity 都必须从 Session 类中获取一个已经打开的 session ,或者,如果没有找到有效的 session ,则创建一个新 session 。

正如官方网站所说,您必须在每个要向 Facebook 发出请求的 Activity 中管理 session 生命周期。
UiLifecycleHelper是一个非常有用的类,可以帮助您管理 Activity 生命周期中的 session 状态(例如,此类的 onPause() 方法处理删除在调用它的 Activity 中添加的回调)

定义 session 类是为了更好地控制 Activity 中的用户身份验证,并保证 token 缓存的自动管理。 Here您可以找到更多详细信息。

关于android - 使用共享首选项/ session 使用 Facebook-Android-SDK 3.0 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16140771/

相关文章:

c# - 在 Visual Studio 2015 中调试 native Android 库时断点不起作用

php - cakephp3 读取组件中的 session

java - 销毁 Spring 中的前一个 session

mysql - 我是否需要为在我的网站上注册的所有用户创建 mysql 帐户或创建 1 个 mysql 用户并将证书传递给所有用户

delphi - DataSnap 和数据库连接/登录

java - 带图标的菜单项溢出?

java - 在 Android 上以编程方式设置 View 的高度

android - 使用 xml 在 android 中自定义形状

php - 使用 mysql 的电子邮件和密码登录

php - 用于移动应用程序的 Laravel RESTful API 身份验证