简体   繁体   English

如何获取用户信息。 使用Android Facebook SDK?

[英]How to get the user info. using the android facebook sdk?

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

                    }
                }
            });
        }

I have tried follow the facebook doc to get the user info when at the onSessionStateChange function, the problem is , it is weird that I follow the offical doc and it shows 我曾尝试在onSessionStateChange函数中遵循facebook doc来获取用户信息,问题是,我遵循官方文档很奇怪,它显示

Request.executeMeRequestAsync is depreciate , so I wonder how to implement get the user info in latest facebook sdk 3.6 ? Request.executeMeRequestAsync已贬值,所以我想知道如何在最新的Facebook SDK 3.6中实现获取用户信息? What I would like to do is get the user info if the user logined. 我想做的就是在用户登录后获取用户信息。 Thanks a lot 非常感谢

Update: 更新:

Anyway I would also like to ask whether this way to implement login is correct? 无论如何,我也想问一下这种登录方式是否正确? There are two place in my app need to login 我的应用程序中有两个地方需要登录

The first one is inside a fragment 第一个在片段内

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

}

The other one is inside another activity 另一个在另一个活动中

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

}

Should I implement the get user info code in all activities? 我应该在所有活动中实施获取用户信息代码吗? thanks 谢谢

Okay, Use below code. 好的,使用下面的代码。

//Define textview to print detail //定义textview以打印细节

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

// Code to retrieve data from FB //从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);
                }
            }
        });

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

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