如何获取用户信息。使用android facebook sdk?

时间:2014-02-13 09:51:43

标签: android facebook facebook-graph-api

if (state.isOpened()) {

            // Request user data and show the results
            Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

                @Override
                public void onCompleted(GraphUser user, Response response) {
                    if (user != null) {
                        // Display the parsed user info

                    }
                }
            });
        }

我已经尝试按照facebook doc获取用户信息,在onSessionStateChange函数中,问题是,我跟随官方文档并显示

很奇怪

Request.executeMeRequestAsync是折旧的,所以我想知道如何在最新的facebook sdk 3.6中获取用户信息?我想要做的是在用户登录时获取用户信息。非常感谢

更新

无论如何我还想问一下这种实现登录的方式是否正确?我的应用程序中有两个位置需要登录

第一个是片段

public class Home extends Fragment {
    public View rootView;
    public ImageView HomeBg;
    public ImageView buttonLoginLogout;
    public TextView chi;
    public TextView eng;
    public ColorStateList oldColor;
    public SharedPreferences prefs;
    public EasyTracker tracker = null;

    //Facebook login
    private Session.StatusCallback statusCallback = new SessionStatusCallback();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        tracker = EasyTracker.getInstance(getActivity());

        getActivity().getActionBar().hide();

        rootView = inflater.inflate(R.layout.home, container, false);
        buttonLoginLogout = (ImageView) rootView.findViewById(R.id.home_connectFB);
        eng = (TextView) rootView.findViewById(R.id.btn_eng);
        chi = (TextView) rootView.findViewById(R.id.btn_chi);

        if (Utility.getLocale(getActivity()).equals("TC")) {
            chi.setTextColor(getActivity().getResources().getColor(
                    android.R.color.white));
            oldColor = eng.getTextColors();
        } else {
            eng.setTextColor(getActivity().getResources().getColor(
                    android.R.color.white));
            oldColor = chi.getTextColors();

        }

        eng.setOnClickListener(setChangeLangListener("EN"));
        chi.setOnClickListener(setChangeLangListener("TC"));

        //Facebook login
        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

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

        updateView();

        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
        tracker.set(Fields.SCREEN_NAME, "Landing Page " + Utility.getLocale(getActivity()));
        tracker.send(MapBuilder.createAppView().build());
    }

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

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

    @Override
    public 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()) {
            buttonLoginLogout.setImageResource(R.drawable.landing_btn_take_a_selfie);
            buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) { 
                    ((LandingPage)getActivity()).tabHost.setCurrentTab(2);
                }
            });
        } else {
            buttonLoginLogout.setImageResource(R.drawable.landing_btn_connect_facebook);
            buttonLoginLogout.setOnClickListener(new View.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));
        } else {
            Session.openActiveSession(getActivity(), this, true, statusCallback);
        }
    }


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

    public OnClickListener setChangeLangListener(final String lang) {
        OnClickListener changeLangListener = new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Configuration config = new Configuration(getResources().getConfiguration());

                if (Utility.getLocale(getActivity()).equals("TC") && lang.equals("EN")) {
                    tracker.send(MapBuilder.createEvent("menu_click","language", "switchEN", null).build());
                    config.locale = Locale.ENGLISH;
                    chi.setTextColor(oldColor);
                    eng.setTextColor(getActivity().getResources().getColor(
                            android.R.color.white));
                } else if (Utility.getLocale(getActivity()).equals("EN") && lang.equals("TC")) {
                    tracker.send(MapBuilder.createEvent("menu_click","language", "switchTC", null).build());
                    config.locale = Locale.TRADITIONAL_CHINESE;
                    eng.setTextColor(oldColor);
                    chi.setTextColor(getActivity().getResources().getColor(
                            android.R.color.white));
                }

                getResources().updateConfiguration(config,getResources().getDisplayMetrics());

                onConfigurationChanged(config);
            }
        };
        return changeLangListener;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
      Intent intent = getActivity().getIntent();
      intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
      getActivity().finish();
      startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        AppEventsLogger.activateApp(getActivity(),getResources().getString(R.string.app_id));
    }

}

另一个是在另一个活动中

public class SharePicForm extends Activity {

    private final String TAG = "SharePicForm";
    public ImageView photoArea;
    public ImageView sharePhotoBtn;
    public EditText shareContent;
    public Bitmap mBitmap;
    public Context ctx;
    public String shareTxt;
    public String fileUri;
    public static boolean isShowForm = true;
    public ProgressDialog pd;
    public EasyTracker tracker = null;

    //Facebook share
    private PendingAction pendingAction = PendingAction.NONE;
    private enum PendingAction {
        NONE, POST_PHOTO
    }
    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        tracker = EasyTracker.getInstance(this);

        setContentView(R.layout.share_pic_form);
        ctx = this;

        Utility.setHeader(this,R.string.selfie_header,false);

        Session session = Session.getActiveSession();
        if (session == null) {
            if (savedInstanceState != null) {
                session = Session.restoreSession(this, null, callback, 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(callback));
            }
        }

        photoArea = (ImageView) findViewById(R.id.photo_area);
        shareContent = (EditText) findViewById(R.id.share_content);

        if (getIntent() != null) {
            Intent intent = getIntent();
            fileUri = (String) intent.getStringExtra("photo");
        } else if (savedInstanceState != null){
            mBitmap = (Bitmap) savedInstanceState.getParcelable("bitmap") == null ? null : (Bitmap) savedInstanceState.getParcelable("bitmap");
        }

        FileInputStream inputStream;

        try {
            File imgSelected = new File(fileUri);
            if (imgSelected.exists()) {
                inputStream = new FileInputStream(imgSelected);
                mBitmap = Utility.decodeBitmap(inputStream, 1280, 960);
                photoArea.setImageBitmap(mBitmap);
                sharePhotoBtn = (ImageView) findViewById(R.id.share_submit);
                sharePhotoBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (mBitmap != null && FormValidation.hasText(shareContent)) {
                            try {
                                File imageToShare = saveBitmapToStorage();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            shareTxt = shareContent.getText().toString();
                            performPublish(PendingAction.POST_PHOTO);                           
                            //new FormSubmit(ctx,easyTracker).execute("shareImg",imageToShare, textToShare);
                        }
                    }
                });
            } else {
                Toast.makeText(ctx, ctx.getResources().getString(R.string.get_photo_error), Toast.LENGTH_SHORT).show();
                finish();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private File saveBitmapToStorage () throws IOException{
        String path = Environment.getExternalStorageDirectory().toString();
        File outputFile = new File(path, "temp.jpg");
        FileOutputStream out = new FileOutputStream(outputFile);
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
        return outputFile;
    }

    //Facebook share 
    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (pendingAction != PendingAction.NONE &&
                (exception instanceof FacebookOperationCanceledException ||
                exception instanceof FacebookAuthorizationException)) {
                new AlertDialog.Builder(SharePicForm.this)
                    .setTitle(ctx.getResources().getString(R.string.error))
                    .setMessage(ctx.getResources().getString(R.string.get_permission_error))
                    .setPositiveButton(ctx.getResources().getString(R.string.close), null)
                    .show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
    }

    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions");
    }

    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;
        if (previouslyPendingAction == PendingAction.POST_PHOTO)
            postPhoto();
    }

    private void performPublish(PendingAction action) {
        Log.d(TAG,"Perform publish");
        Session session = Session.getActiveSession();
        if (session != null) {
            Log.d(TAG,"Session != null");
            pendingAction = action;
            if (hasPublishPermission()) {
                Log.d(TAG,"Has permission");
                // We can do the action right away.
                handlePendingAction();
                return;
            } else if (session.isOpened()) {
                Log.d(TAG,"Open session");
                // We need to get new permissions, then complete the action when we get called back.
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, "publish_actions"));
                return;
            } else {
                onClickLogin();
            }
        } else{
            Log.d(TAG,"Session == null");
        }
    }

    private void onClickLogin() {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            session.openForRead(new Session.OpenRequest(this).setCallback(callback));
        } else {
            Session.openActiveSession(this, true, callback);
        }
    }

    private void postPhoto() {
        Log.d(TAG,"postPhoto: " + hasPublishPermission());
        if (hasPublishPermission()) {
            if (mBitmap != null) {
                Request request = Request.newUploadPhotoRequest(
                        Session.getActiveSession(),mBitmap, new Request.Callback() {                        
                            @Override
                            public void onCompleted(Response response) {
                                pd.dismiss();
                                if (response.getError() == null) {
                                    Utility.showDialog(ctx,"success_photo",tracker);
                                } else {
                                    Log.d(TAG,response.getError().getErrorMessage());
                                    Toast.makeText(ctx, response.getError().getErrorMessage(), Toast.LENGTH_LONG).show();
                                    Utility.showDialog(ctx,"error",tracker);
                                }
                            }
                        });
                Bundle params = request.getParameters();

                if (shareTxt != null) 
                    params.putString("message", shareTxt);

                request.setParameters(params);
                request.executeAsync();
                pd = ProgressDialog.show(ctx, ctx.getResources().getString(R.string.sys_info),ctx.getResources().getString(R.string.publishing));
            }
        } else {
            pendingAction = PendingAction.POST_PHOTO;
        }
    }

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

    @Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(callback);
        EasyTracker.getInstance(this).activityStart(this);
        tracker.set(Fields.SCREEN_NAME, "Image_entryForm " + Utility.getLocale(this));
        tracker.send(MapBuilder.createAppView().build());
    }

    @Override
    public void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(callback);
        EasyTracker.getInstance(this).activityStop(this);
    }

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

    @Override
    public void onResume() {
        super.onResume();
        AppEventsLogger.activateApp(this,getResources().getString(R.string.app_id));
    }

}

我应该在所有活动中实现获取用户信息代码吗?感谢

1 个答案:

答案 0 :(得分:1)

好的,请使用以下代码。

//定义textview以打印详细信息

TextView mfirstname, mlastname, middlename, mfullname, mbirthdate,
            mfacebookLink, mfacebookId, mfacebookUnm, mgender, mEmail;

//从FB中检索数据的代码

Session.openActiveSession(this, true, new Session.StatusCallback() {
            // callback when session changes state
            @Override
            public void call(Session session, SessionState state,
                    Exception exception) {
                if (session.isOpened()) {
                    // make request to the /me API
                    Request.executeMeRequestAsync(session,
                            new Request.GraphUserCallback() {
                                @Override
                                public void onCompleted(GraphUser user,
                                        Response response) {
                                    if (user != null) {
                                        mfirstname.setText(user.getFirstName());
                                        mlastname.setText(user.getLastName());
                                        middlename.setText(user.getMiddleName());
                                        mfullname.setText(user.getName());
                                        mbirthdate.setText(user.getBirthday());
                                        mfacebookLink.setText(user.getLink());
                                        mfacebookId.setText(user.getId());
                                        mfacebookUnm.setText(user.getUsername());
                                        String gender = user.asMap()
                                                .get("gender").toString();
                                        String email = user.asMap()
                                                .get("email").toString();
                                        mgender.setText(gender);
                                        mEmail.setText(email);

                                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                                                .permitAll().build();
                                        StrictMode.setThreadPolicy(policy);


                } else {
                    Toast.makeText(getApplicationContext(), "Error...",
                            Toast.LENGTH_LONG);
                }
            }
        });