Facebook SDK:在我的 Android 应用程序中检索用户信息

Posted

技术标签:

【中文标题】Facebook SDK:在我的 Android 应用程序中检索用户信息【英文标题】:Facebook SDK: retrieve User information in my Android application 【发布时间】:2014-07-14 11:06:45 【问题描述】:

我是 android 开发的新手,我知道有很多关于我要问的示例,但我无法真正理解它们,而 facebook doc https://developers.facebook.com/docs/android/graph/ 中的示例非常复杂

我在我的代码中集成了 Facebook,如下所示

package com.example.museum;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.model.GraphUser;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;


public class MainActivity extends Activity implements  android.view.View.OnClickListener
    Facebook fb;
    ImageView pic, button, signup;
    SharedPreferences sp;
    TextView welcome;



    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

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

        String APP_ID = getString(R.string.app_id);
        fb = new Facebook(APP_ID);

        welcome = (TextView)findViewById(R.id.welcome);

        sp = getPreferences(MODE_PRIVATE);
        String access_token = sp.getString("access_token", null);
        long expires = sp.getLong("access_expires", 0);

        if (access_token != null)

            fb.setAccessToken(access_token);
        
        if (expires != 0)

            fb.setAccessExpires(expires);
        





        button = (ImageView) findViewById(R.id.login);


        pic = (ImageView) findViewById(R.id.picture_pic);
        signup = (ImageView)findViewById(R.id.signup);

        signup.setOnClickListener(new View.OnClickListener() 

            @Override
            public void onClick(View v) 
                // TODO Auto-generated method stub
                Intent i = new Intent(getApplicationContext(),One.class);
                startActivity(i);
            
        );


        button.setOnClickListener(this);
        userInfo();

    

    @SuppressWarnings("deprecation")
    private void userInfo() 
        // TODO Auto-generated method stub

        List<String> permissions = new ArrayList<String>();
        permissions.add("email");



        if(fb.isSessionValid())
            button.setImageResource(R.drawable.logout_button);
            signup.setVisibility(ImageView.INVISIBLE);

            //pic.setVisibility(ImageView.VISIBLE);
            JSONObject obj = null;
            URL img_value = null;




            try 

                String jsonUser = fb.request("me");
                obj = Util.parseJson(jsonUser);

                String id = obj.optString("id");
                String name = obj.optString("name");

                Log.d("NAME", name);

                 // getting email of the user
                //String email = obj.optString("email");

                //for (int i = 0; i< 100 ; i++)Log.d("E_MAIL", email);

                welcome.setText("Welcome to Museum, " + name);

//              img_value = new URL("https://graph.facebook.com/"+id+"/picture?height=100&type=normal&width=100&redirect=0");
//              Bitmap bmp = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
//              pic.setImageBitmap(bmp);
//              pic.setVisibility(ImageView.VISIBLE);


             catch (FacebookError e) 
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d("Error", "FacebookError");
            catch (JSONException e) 
                Log.d("Error", "JSONException");
                e.printStackTrace();


            catch (IOException e) 
                Log.d("Error", "IOException");
                e.printStackTrace();

            catch (Exception e) 
                // TODO Auto-generated catch block
                e.printStackTrace();
                for (int i = 0; i< 50 ; i++)Log.d("Error", "Exception");
            



        else
            button.setImageResource(R.drawable.login_button);
            pic.setVisibility(ImageView.INVISIBLE);





        

    



    @Override
    public void onClick(View v) 
        // TODO Auto-generated method stub

        if(fb.isSessionValid())
            // button close our session - log out of facebook
            try 
                fb.logout(getApplicationContext());
                userInfo();
             catch (MalformedURLException e) 
                // TODO Auto-generated catch block
                e.printStackTrace();
             catch (IOException e) 
                // TODO Auto-generated catch block
                e.printStackTrace();
            

        else 
            //login to facebook 
            fb.authorize(MainActivity.this, new Facebook.DialogListener() 

                @Override
                public void onFacebookError(FacebookError e) 
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, "fbError", Toast.LENGTH_SHORT).show();

                

                @Override
                public void onError(DialogError e) 
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, "onError", Toast.LENGTH_SHORT).show();

                

                @Override
                public void onComplete(Bundle values) 
                    // TODO Auto-generated method stub
                    Editor editor = sp.edit();
                    editor.putString("access_token", fb.getAccessToken());
                    editor.putLong("access_expires", fb.getAccessExpires());
                    editor.commit();
                    userInfo();

                

                @Override
                public void onCancel() 
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show();

                
            );
        
    

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    fb.authorizeCallback(requestCode, resultCode, data);








我需要检索用户信息,例如他的电子邮件、他的位置、他的生日以及他喜欢的最重要的页面,我知道我必须使用权限,请告诉我该怎么做。

任何帮助将不胜感激。

【问题讨论】:

【参考方案1】:

您需要发出新的回调请求。像这样:

Session.OpenRequest openRequest = new Session.OpenRequest(Login.this);
    openRequest.setPermissions(Arrays.asList("email", "user_birthday"));
    openRequest.setCallback(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 request = Request.newMeRequest(session,
                        new Request.GraphUserCallback() 

                            // callback after Graph API response with user
                            // object
                            @Override
                            public void onCompleted(GraphUser gUser,
                                    Response response) 
                                if (gUser != null) 
                                    String email = gUser.getProperty("email").toString();
                                    String firstName = gUser.getFirstName();
                                    String lastName = gUser.getLastName();
                                    String username = gUser.getUsername();
                                    String birthday = gUser.getBirthday();
                                
                            

                        );
                request.executeAsync();

            
        
    
    );

【讨论】:

您的意思是代替我的方法 userInfo() 还是除此之外?在哪里添加它我有点困惑 @مروانعلىفهمى 你应该可以把它放在你的 userInfo() 方法中 那么什么是“用户”,它是一个捆绑包吗?因为我不明白在做什么! 我这样做并试图在日志中输出它,但我什么也没得到......确定我只是替换了 userInfo() 中的内容并且它可以工作 @مروانعلىفهمى 你想记录什么?

以上是关于Facebook SDK:在我的 Android 应用程序中检索用户信息的主要内容,如果未能解决你的问题,请参考以下文章

使用适用于 Android 的 Facebook Unity SDK 登录 facebook 时应用程序强制关闭

登录onActivityResult Android后Facebook SDK应用程序崩溃

Android:facebook sdk注销问题?

Facebook SDK 登录回调永远不会被称为 android

Facebook Android SDK 注销监听器

使用 Facebook SDK Login (iOs/Android) 登录 Facebook @ Web?