1

短短一周的时间里,我一直把头撞在墙上,试图将我的头包裹在 Facebook 最新的 Android SDK (3.0) 上,在我看来,Facebook 已经设法使最初没有被破坏的东西过于复杂化。

我要做的就是让 onCreate 中的代码在 onClick 中工作。我为实现这一目标而编写的活动代码如下,是的,它目前在启动时可以工作。(登录用户,向我的 api 发出请求并执行其假设的操作。)

我不需要也不想管理 Facebook 的“会话”,而不是绝对需要,我只是想让用户使用他们的 fb 凭据登录,打开一个会话,发出一个请求来获取用户信息,发送它直到我的 API 和使用我自己的 API/共享首选项/会话的接管。如果更容易将我指向一个片段的方向,该片段将说明我如何做到这一点。我在下面设置的权限与编辑我的活动相比,这也不仅仅是回答我的问题。

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 Old_FB_Login_Activity 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;
    private Button buttonLogin; 

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

        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) {

        } 
    }

   /* 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_expires);



                        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("first_name", firstName);
                        }


                        if(user.getLastName() != null){
                            String lastName = user.getLastName();
                            Log.i("last name_3", lastName);
                            params.put("last_name", 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("fb_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.createFBLoginSession(json);
                                    } catch (JSONException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                    Intent i = new Intent(getApplicationContext(), TabHostFragmentActivity.class);
                                    startActivity(i);
                                    finish();



                            }
                        });










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

1 回答 1

0

您要查看的关键内容是 UiLifecycleHelper,https://developers.facebook.com/docs/reference/android/3.0/UiLifecycleHelper/。您只需在活动的 onCreate 方法中创建 this 的实例,并传递 Session.StatusCallback 的实例来处理会话状态的更改(打开、关闭等)。然后,在活动的几个生命周期方法(onCreate、onResume 等)中插入对 UiLifecycleHelper 的调用。这应该取代旧的 FacebookActivity 过去所做的所有事情。

然后只需使用 LoginButton 启动登录过程https://developers.facebook.com/docs/reference/android/3.0/LoginButton

于 2013-04-29T05:22:37.180 回答