简体   繁体   English

使用共享首选项/会话使用Facebook-Android-SDK 3.0登录

[英]Login with Facebook-Android-SDK 3.0 using Shared Preferences/Session

For a long while I was using a login almost identical to the one found in this tutorial until I realized it was deprecated. 在很长一段时间里,我一直使用与本教程中找到的登录名几乎相同的登录名,直到我意识到它已被弃用。

So like a good developer I decided to try upgrading my login to Facebook Android 3.0 SDK, but as I looked at the documentation I couldn't help but wonder why Facebook would over complicate their login when the old one worked so well. 因此,像一个优秀的开发人员一样,我决定尝试将登录名升级到Facebook Android 3.0 SDK,但是当我查看文档时,我不禁想知道,如果旧的登录名如此出色,为什么Facebook会使登录名变得过于复杂。

My current code is below , but I'm a bit confused. 我当前的代码在下面,但我有些困惑。 I used to simply make an authorize request to Facebook, get some info from them, compare it to my db and if it matched up id save some info to shared prefs and open the home activity of my app. 我以前只是简单地向Facebook发出授权请求,从中获取一些信息,将其与我的数据库进行比较,如果它与id匹配,则将一些信息保存到共享的首选项中并打开我的应用程序的家庭活动。 However, with the 3.0 and "sessions" I'm a bit confused: 但是,对于3.0和“会话”,我有点困惑:

  1. Do I have to use these "sessions" in all my activities? 我在所有活动中都必须使用这些“会话”吗?
  2. If so, do they persist throughout my app? 如果是这样,它们是否在我的整个应用程序中持续存在?
  3. What is the point of sessions if we already have shared prefs? 如果我们已经有共享偏好,那么会议的重点是什么?

The code: 编码:

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

You must always refer to the unique Session class. 您必须始终引用唯一的Session类。 Every activity has to take an already opened session from the Session class or, if no valid sessions are found, created a new one. 每个活动都必须从Session类中获取一个已经打开的会话,或者,如果找不到有效的会话,则创建一个新的会话。

As the official site said you have to manage the session lifecycle in every activity that want to make request to Facebook. 正如官方网站所说,您必须在每个要向Facebook请求的活动中管理会话生命周期。
The UiLifecycleHelper is a very useful class that can help you manage the session state among the activities lifecycle (for example the onPause() method of this class deal with the removal of the callback added in the activity in which it's called) UiLifecycleHelper是一个非常有用的类,可以帮助您管理活动生命周期中的会话状态(例如,此类的onPause()方法处理的是删除在调用它的活动中添加的回调)

The Session class is defined in order to give a better control on the authentication of the user among the activities and guarantees automatic management of the token cache. 定义Session类是为了更好地控制活动中用户的身份验证,并确保自动管理令牌缓存。 Here you can find more details. 在这里您可以找到更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM