【问题标题】:Android - get facebook profile pictureAndroid - 获取 facebook 个人资料图片
【发布时间】:2013-11-20 05:27:55
【问题描述】:

我不知道为什么,但是当我尝试获取用户的个人资料图片时,我总是得到空值。我是否需要设置一些特定的权限才能获得访问权限?

下面是我的方法:

public static Bitmap getFacebookProfilePicture(String userID) throws SocketException, SocketTimeoutException, MalformedURLException, IOException, Exception
{
   String imageURL;

   Bitmap bitmap = null;
   imageURL = "http://graph.facebook.com/"+userID+"/picture?type=large";
   InputStream in = (InputStream) new URL(imageURL).getContent();
   bitmap = BitmapFactory.decodeStream(in);

   return bitmap;
}

Bitmap bitmap = getFacebookProfilePicture(userId);

我得到空值。我不知道为什么?任何帮助都是可观的。

【问题讨论】:

  • 你在facebook开发者页面中设置了应用哈希吗?其他 Facebook 电话是否有效?你检查过你的日志吗?您可能有一个不正确的哈希值(这种情况经常发生)。
  • @JeffreyKlardie 你甚至不需要 facebook api 来获取个人资料照片。
  • 你是对的。我没有意识到这一点。我添加了一个略有不同的答案;我使用URL.openConnection().getInputStream() 而不是URL.getContent();

标签: android facebook profile


【解决方案1】:

我使用了这个代码,我得到了个人资料图片,

fbUsrPicURL = "http://graph.facebook.com" + File.separator
                    + String.valueOf(fbUID) + File.separator + "picture?type=large";

【讨论】:

    【解决方案2】:

    这应该可行:

    public static Bitmap getFacebookProfilePicture(String userID){
        URL imageURL = new URL("https://graph.facebook.com/" + userID + "/picture?type=large");
        Bitmap bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
    
        return bitmap;
    }
    
    Bitmap bitmap = getFacebookProfilePicture(userId);
    

    编辑:

    根据cmets中@dvpublic的建议,使用“https”代替“http”解决了无法下载图像的问题。

    【讨论】:

    • 在我看来,最后一个 SDK 执行此方法停止工作。有谁知道发生了什么? BitmapFactory.decodeStream 现在总是返回 null
    • 我怀疑,SDK 不是罪魁祸首,问题在于重定向。尝试在浏览器中打开链接“graph.facebook.com/USER_UID/picture” - 将打开链接“httpS://fbcdn-profile-a.akamaihd.net...”。当原始协议和重定向协议相同时,自动重定向会自动工作。因此,尝试从“httpS://graph.facebook.com/USER_UID/picture”加载图像并确保调用了 HttpURLConnection.setFollowRedirects(true) 或 conn.setInstanceFollowRedirects(true)。然后 BitmapFactory.decodeStream 将再次工作。
    • 出现错误 > SkAndroidCodec::NewFromStream 返回 null
    【解决方案3】:

    网址看起来不错。

    所以问题出在您的连接上。 URL.getContent() 真的返回流吗?因为如果 BitmapFactory 为 null,它也会返回 null。

    试试这个:

    Bitmap bitmap = null;
    URL url = new URL(http://graph.facebook.com/"+userID+"/picture?type=large);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
       InputStream in = new BufferedInputStream(urlConnection.getInputStream());
       bitmap = BitmapFactory.decodeStream(in);
    }
    finally {
          urlConnection.disconnect();
    }
    

    【讨论】:

      【解决方案4】:

      检查用户 ID 使用这个 url

      imgurl="https://graph.facebook.com/"+user.getId()+"/picture";
      

      【讨论】:

        【解决方案5】:

        这应该可以解决。但一定要静态访问 setfollowredirects 即 HttpURLConnection.setFollowRedirects(HttpURLConnection.getFollowRedirects());

        url = new URL("https://graph.facebook.com/ID/picture?type=small");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();                                           HttpURLConnection.setFollowRedirects(HttpURLConnection.getFollowRedirects());
        connection.setDoInput(true);
        connection.connect();
        input = connection.getInputStream();
        
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(input, null, options);
        
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 300, 300);
        
         // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Config.RGB_565;
        myBitmap= BitmapFactory.decodeStream(input, null, options);
        

        或

        url = new URL("https://graph.facebook.com/ID/picture?type=small");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();                                                HttpURLConnection.setFollowRedirects(HttpURLConnection.getFollowRedirects());
        connection.setDoInput(true);
        connection.connect();
        input = connection.getInputStream();
        myBitmap= BitmapFactory.decodeStream(input);
        

        希望对你有帮助

        【讨论】:

          【解决方案6】:

          这可能是你在主线程中运行你的方法 使用

          if( android.os.Build.VERSION.SDK_INT > 9 )
          {
            try
            {
              StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
              StrictMode.setThreadPolicy( policy );
            }
          }
          

          【讨论】:

            【解决方案7】:
               public static Bitmap getFacebookProfilePicture(String userID)
                            throws SocketException, SocketTimeoutException,
                            MalformedURLException, IOException, Exception {
                        String imageURL;
                        Bitmap bitmap = null;
                        imageURL = "http://graph.facebook.com/" + userID
                                + "/picture?type=large";
            
                         URL url1 = new URL(imageURL);
                            HttpURLConnection ucon1 = (HttpURLConnection) url1.openConnection();
                            ucon1.setInstanceFollowRedirects(false);
                            URL secondURL1 = new URL(ucon1.getHeaderField("Location"));
                        InputStream in = (InputStream) new URL(imageURL).getContent();
                        bitmap = BitmapFactory.decodeStream(in);
                        return bitmap;
                    }
            

            使用此代码.....

            【讨论】:

            • 为什么我们应该使用这个代码?它是如何工作的?纯代码答案可能会被删除,因为它们不能帮助其他人了解如何解决问题,而只是为他们解决问题,
            【解决方案8】:

            你得到 null 因为对 URL.openConnection() 的调用(或任何其他获取图像的机制)是异步的。它在您的行之后返回:return bitmap;。因此位图始终为空。

            我建议改用回调。

            这就是我所做的:

            final AQuery androidQuery = new AQuery(this);
            
                    AjaxCallback<byte[]> imageCallback = new AjaxCallback<byte[]>() {
            
                        @Override
                        public void callback(String url, byte[] avatar, AjaxStatus status) {
            
                            if (avatar != null) {
                                save(avatar);
                            } else {
                                Log.e(TAG, "Cannot fetch third party image. AjaxStatus: " + status.getError());
                            }
                        }
            
                    };
            
                    androidQuery.ajax(imageUrl, byte[].class, imageCallback);
            

            Android 查询允许您获取不同格式的图像(例如字节数组、位图等)。那里还有其他库,但想法是一样的。

            【讨论】:

              【解决方案9】:

              只需使用毕加索。添加毕加索库,然后使用这个简单的行代码:

              userpicture = (ImageView) row.findViewById(R.id.postuserid);
              
              Picasso.with(context)
                     .load("https://graph.facebook.com/" + userID+ "/picture?type=large")
                     .into(userpicture);
              

              【讨论】:

              • 如果您使用 Picasso,那么由于缓存,它会加载相同的图像,因此当配置文件更改时,您将看不到使用 Picasso 更新的图像。
              【解决方案10】:

              使用 facebook ProfilePictureView 而不是 Imageview

              <com.facebook.login.widget.ProfilePictureView
                  android:id="@+id/friendProfilePicture"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_centerInParent="true"
                  facebook:preset_size="small"/>
              

              之后,您可以在代码中像这样设置 facebook id

              ProfilePictureView profilePictureView;
              
              profilePictureView = (ProfilePictureView) findViewById(R.id.friendProfilePicture);
              
              profilePictureView.setProfileId(userId);
              

              它有效.. 您还可以将ProfilePictureView的大小设置为小/正常/大/自定义

              【讨论】:

              • 如何制作圆形 ProfilePictureView。
              • 那么您需要为此制作自定义 ProfilePictureView。参考链接:stackoverflow.com/questions/23464707/…
              • 哦,谢谢伙计!你是救生员。挣扎了一个小时
              【解决方案11】:

              我是这样做的:

              从Facebook的Image Url获取Bitmap:

              String imageUrl = "http://graph.facebook.com/103407310026838/picture?type=large&width=1000&height=1000";
              
              Bitmap bitmap = getFacebookProfilePicture(imageUrl);
              
              位图的

              函数:

              private Bitmap getFacebookProfilePicture(String url){
                  Bitmap bitmap = null;
                  HttpGet httpRequest = new HttpGet(URI.create(url));
                  HttpClient httpclient = new DefaultHttpClient();
                  HttpResponse mResponse;
                  try {
                  mResponse = (HttpResponse) httpclient.execute(httpRequest);
                  HttpEntity entity = mResponse.getEntity();
                      BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                      bitmap = BitmapFactory.decodeStream(bufHttpEntity.getContent());
                      httpRequest.abort();
                  }
                  catch(Exception e){
                      e.printStackTrace();
                  }
                 return bitmap;
               }
              

              完成了。

              【讨论】:

                【解决方案12】:
                imgUrl = "https://graph.facebook.com/" + user_id + "/picture?type=large";
                

                然后Picasso.with(getApplicationContext()).load(imgUrl).into(imageView);

                【讨论】:

                  【解决方案13】:

                  我认为问题出在

                  imageURL = "**http**://graph.facebook.com/"+userID+"/picture?type=large";
                  

                  使用https insted of http

                  【讨论】:

                    【解决方案14】:
                    private void importFbProfilePhoto() {
                    
                        if (AccessToken.getCurrentAccessToken() != null) {
                    
                            GraphRequest request = GraphRequest.newMeRequest(
                                    AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                                        @Override
                                        public void onCompleted(JSONObject me, GraphResponse response) {
                    
                                            if (AccessToken.getCurrentAccessToken() != null) {
                    
                                                if (me != null) {
                    
                                                    String profileImageUrl = ImageRequest.getProfilePictureUri(me.optString("id"), 500, 500).toString();
                                                    Log.i(LOG_TAG, profileImageUrl);
                    
                                                }
                                            }
                                        }
                                    });
                            GraphRequest.executeBatchAsync(request);
                        }
                    }
                    

                    【讨论】:

                    • ImageRequest 很好用,但它是com.facebook.internal 的一部分。此类的文档警告不支持使用这些类。风险自负!
                    【解决方案15】:

                    您必须调用 GraphRequest API 来获取当前头像的 URL。

                    Bundle params = new Bundle();
                    params.putString("fields", "id,email,picture.type(large)");
                    new GraphRequest(AccessToken.getCurrentAccessToken(), "me", params, HttpMethod.GET,
                            new GraphRequest.Callback() {
                                @Override
                                public void onCompleted(GraphResponse response) {
                                    if (response != null) {
                                        try {
                                            JSONObject data = response.getJSONObject();
                                            if (data.has("picture")) {
                                                String profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
                                                Bitmap profilePic = BitmapFactory.decodeStream(profilePicUrl.openConnection().getInputStream());
                                                // set profilePic bitmap to imageview
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                    }).executeAsync();
                    

                    希望对你有帮助!

                    【讨论】:

                    • 别忘了从String url:BitmapFactory.decodeStream(new URL(url).openConnection().getInputStream());创建一个新的URL对象
                    【解决方案16】:

                    对我有用的完整解决方案!

                    import android.app.Dialog;
                    import android.content.Intent;
                    import android.support.v7.app.AppCompatActivity;
                    import android.os.Bundle;
                    import android.text.Html;
                    import android.view.View;
                    import android.widget.Button;
                    import android.widget.TextView;
                    
                    import com.facebook.AccessToken;
                    import com.facebook.CallbackManager;
                    import com.facebook.FacebookCallback;
                    import com.facebook.FacebookException;
                    import com.facebook.FacebookSdk;
                    import com.facebook.GraphRequest;
                    import com.facebook.GraphResponse;
                    import com.facebook.login.LoginResult;
                    import com.facebook.login.widget.LoginButton;
                    import com.facebook.login.widget.ProfilePictureView;
                    import com.facebook.share.model.ShareLinkContent;
                    import com.facebook.share.widget.ShareDialog;
                    
                    import org.json.JSONException;
                    import org.json.JSONObject;
                    
                    public class MainActivity extends AppCompatActivity {
                        CallbackManager callbackManager;
                        Button share,details;
                        ShareDialog shareDialog;
                        LoginButton login;
                        ProfilePictureView profile;
                        Dialog details_dialog;
                        TextView details_txt;
                    
                        @Override
                        protected void onCreate(Bundle savedInstanceState) {
                            super.onCreate(savedInstanceState);
                            FacebookSdk.sdkInitialize(getApplicationContext());
                            setContentView(R.layout.activity_main);
                    
                            callbackManager = CallbackManager.Factory.create();
                            login = (LoginButton)findViewById(R.id.login_button);
                            profile = (ProfilePictureView)findViewById(R.id.picture);
                            shareDialog = new ShareDialog(this);
                            share = (Button)findViewById(R.id.share);
                            details = (Button)findViewById(R.id.details);
                            login.setReadPermissions("public_profile email");
                            share.setVisibility(View.INVISIBLE);
                            details.setVisibility(View.INVISIBLE);
                            details_dialog = new Dialog(this);
                            details_dialog.setContentView(R.layout.dialog_details);
                            details_dialog.setTitle("Details");
                            details_txt = (TextView)details_dialog.findViewById(R.id.details);
                            details.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    details_dialog.show();
                                }
                            });
                    
                            if(AccessToken.getCurrentAccessToken() != null){
                                RequestData();
                                share.setVisibility(View.VISIBLE);
                                details.setVisibility(View.VISIBLE);
                            }
                            login.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if(AccessToken.getCurrentAccessToken() != null) {
                                        share.setVisibility(View.INVISIBLE);
                                        details.setVisibility(View.INVISIBLE);
                                        profile.setProfileId(null);
                                    }
                                }
                            });
                            share.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    ShareLinkContent content = new ShareLinkContent.Builder().build();
                                    shareDialog.show(content);
                    
                                }
                            });
                            login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
                                @Override
                                public void onSuccess(LoginResult loginResult) {
                    
                                    if(AccessToken.getCurrentAccessToken() != null){
                                        RequestData();
                                        share.setVisibility(View.VISIBLE);
                                        details.setVisibility(View.VISIBLE);
                                    }
                                }
                    
                                @Override
                                public void onCancel() {
                    
                                }
                    
                                @Override
                                public void onError(FacebookException exception) {
                                }
                            });
                    
                        }
                        public void RequestData(){
                            GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject object,GraphResponse response) {
                    
                                    JSONObject json = response.getJSONObject();
                                    try {
                                        if(json != null){
                                            String text = "<b>Name :</b> "+json.getString("name")+"<br><br><b>Email :</b> "+json.getString("email")+"<br><br><b>Profile link :</b> "+json.getString("link");
                                            details_txt.setText(Html.fromHtml(text));
                                            profile.setProfileId(json.getString("id"));
                                        }
                    
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                            Bundle parameters = new Bundle();
                            parameters.putString("fields", "id,name,link,email,picture");
                            request.setParameters(parameters);
                            request.executeAsync();
                        }
                    
                        @Override
                        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                            super.onActivityResult(requestCode, resultCode, data);
                            callbackManager.onActivityResult(requestCode, resultCode, data);
                        }
                    
                    }
                    

                    【讨论】:

                      【解决方案17】:
                      imgUrl = "https://graph.facebook.com/" + user_id + "/picture?type=large";
                      

                      试试这个

                      【讨论】:

                        【解决方案18】:

                        获取个人资料图片 URL 的最佳方式

                        int dimensionPixelSize = getResources().getDimensionPixelSize(com.facebook.R.dimen.com_facebook_profilepictureview_preset_size_large);
                        Uri profilePictureUri= Profile.getCurrentProfile().getProfilePictureUri(dimensionPixelSize , dimensionPixelSize);
                        

                        或

                        Uri profilePictureUri = ImageRequest.getProfilePictureUri(Profile.getCurrentProfile().getId(), dimensionPixelSize , dimensionPixelSize );
                        

                        使用 Glide 显示图像

                        Glide.with(this).load(profilePictureUri)
                                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                                        .into(profilePictureView);
                        

                        没有更多的硬编码字符串

                        【讨论】:

                        • Profile对象中还有一个内置函数可以获取头像:Profile.getCurrentProfile().getProfilePictureUri
                        【解决方案19】:

                        当你提出这样的要求时:

                        http://graph.facebook.com/103407310026838/picture?type=square&type=large
                        

                        它会重定向到其他网址..

                        您需要在 Get 请求中添加一个额外的参数

                        redirect=false
                        

                        这样

                        http://graph.facebook.com/103407310026838/picture?type=square&type=large&redirect=false
                        

                        你会得到一个带有真实图像 url 的 Json..

                        像这样:

                        {
                           "data": {
                              "is_silhouette": true,
                              "url": "https://scontent.xx.fbcdn.net/v/t1.0-1/s200x200/1379841_10150004552801901_469209496895221757_n.jpg?oh=4234dcdfc832a58b9ef7a31c7896c73c&oe=57DD01F8"
                           }
                        }
                        

                        终于发出新请求来获取您在 data->url 中找到的图像

                        【讨论】:

                          【解决方案20】:

                          我总是收到一条回复说FACEBOOK_NON_JSON_RESULT。因此,回顾 Facebook 的图形 API 资源管理器,我注意到一个小复选框,选中了标签重定向。一些谷歌搜索告诉我,我需要为我的GraphRequest 提供一个不允许重定向的参数。因此正确的请求必须是:

                           Bundle params = new Bundle();
                           params.putBoolean("redirect", false);
                          
                               new GraphRequest(
                               AccessToken.getCurrentAccessToken(),
                               "me/picture",
                               params,
                               HttpMethod.GET,
                               new GraphRequest.Callback() {
                                  public void onCompleted(GraphResponse response) {
                                      try {
                                          String picUrlString = (String) response.getJSONObject().getJSONObject("data").get("url");   
                                          //Load picture url in imageView
                                          Glide.with(this).load(picUrlString).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(profilePictureView);
                                      } catch (JSONException | IOException e) {
                                          e.printStackTrace();
                                      }
                                  }
                              }
                           ).executeAsync();                                      
                          

                          【讨论】:

                            【解决方案21】:

                            我搜索了所有模式以在 API 15 上实现这一点,只有这种方法对 Volley 有效:

                            String url = "https://graph.facebook.com/"+ fid +"/picture?type=square";
                                            ImageRequest request = new ImageRequest(url,
                                                    new Response.Listener<Bitmap>() {
                                                        @Override
                                                        public void onResponse(Bitmap bitmap) {
                                                            imageView.setImageBitmap(bitmap);
                                                        }
                                                    }, 0, 0, null,
                                                    new Response.ErrorListener() {
                                                        public void onErrorResponse(VolleyError error) {
                                                            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                                                        }
                                                    });
                                            AppController.getInstance().addToRequestQueue(request);
                            

                            【讨论】:

                              【解决方案22】:
                              Bundle bundle = new Bundle();
                              
                              bundle.putString ("fields", "full_picture,message");
                              
                              new GraphRequest(
                                              AccessToken.getCurrentAccessToken(),
                                              "{page-id}/feed",
                                              bundle,
                                              HttpMethod.GET,
                                              new GraphRequest.Callback() {
                                                  public void onCompleted(GraphResponse response) {
                                          /* handle the result */
                                                      Log.e("TAG", response.toString());
                                                  }
                                              }
                                      ).executeAsync();
                              

                              【讨论】:

                                【解决方案23】:

                                与Glide:

                                userId = loginResult.getAccessToken().getUserId();
                                

                                那么;

                                Glide.with(this)
                                        .load("https://graph.facebook.com/" + userId+ "/picture?type=large")
                                        .into(imgProfile);
                                

                                【讨论】:

                                  【解决方案24】:

                                  从here下载源代码

                                  添加这个依赖:

                                  compile 'com.facebook.android:facebook-android-sdk:4.0.1'
                                  

                                  activity_main.xml

                                  <LinearLayout android:layout_width="match_parent"
                                      android:layout_height="match_parent"
                                      android:orientation="vertical"
                                      xmlns:android="http://schemas.android.com/apk/res/android">
                                  
                                  
                                      <ImageView
                                          android:layout_width="100dp"
                                          android:layout_height="100dp"
                                          android:id="@+id/iv_image"
                                          android:layout_marginTop="10dp"
                                          android:layout_marginBottom="10dp"
                                          android:layout_gravity="center_horizontal"
                                          android:src="@drawable/profile"/>
                                  
                                  
                                      <LinearLayout
                                          android:layout_width="match_parent"
                                          android:orientation="horizontal"
                                          android:layout_height="wrap_content">
                                          <TextView
                                              android:layout_width="100dp"
                                              android:layout_height="40dp"
                                              android:text="Name"
                                              android:gravity="center_vertical"
                                              android:textSize="15dp"
                                              android:textColor="#000000"
                                  
                                              android:layout_marginLeft="10dp"
                                              android:layout_marginTop="10dp"/>
                                  
                                          <TextView
                                              android:layout_width="wrap_content"
                                              android:layout_height="40dp"
                                              android:text="Name"
                                              android:textSize="15dp"
                                              android:id="@+id/tv_name"
                                              android:gravity="center_vertical"
                                              android:textColor="#000000"
                                              android:layout_marginLeft="10dp"
                                              android:layout_marginTop="10dp"/>
                                  
                                      </LinearLayout>
                                  
                                  
                                      <LinearLayout
                                          android:layout_width="match_parent"
                                          android:layout_height="wrap_content"
                                          android:orientation="horizontal">
                                  
                                      <TextView
                                          android:layout_width="100dp"
                                          android:layout_height="40dp"
                                          android:text="Email"
                                          android:gravity="center_vertical"
                                          android:textSize="15dp"
                                          android:layout_below="@+id/tv_name"
                                          android:textColor="#000000"
                                          android:layout_marginLeft="10dp"
                                          android:layout_marginTop="10dp"/>
                                  
                                      <TextView
                                          android:layout_width="wrap_content"
                                          android:layout_height="40dp"
                                          android:layout_below="@+id/tv_name"
                                          android:text="Email"
                                          android:gravity="center_vertical"
                                          android:textSize="15dp"
                                          android:id="@+id/tv_email"
                                          android:textColor="#000000"
                                          android:layout_marginLeft="10dp"
                                          android:layout_marginTop="10dp"/>
                                      </LinearLayout>
                                  
                                      <LinearLayout
                                          android:layout_width="match_parent"
                                          android:layout_height="wrap_content"
                                          android:orientation="horizontal">
                                  
                                          <TextView
                                              android:layout_width="100dp"
                                              android:layout_height="40dp"
                                              android:text="DOB"
                                              android:gravity="center_vertical"
                                              android:textSize="15dp"
                                              android:textColor="#000000"
                                              android:layout_marginLeft="10dp"
                                              android:layout_marginTop="10dp"/>
                                  
                                          <TextView
                                              android:layout_width="wrap_content"
                                              android:layout_height="40dp"
                                              android:layout_below="@+id/tv_name"
                                              android:text="DOB"
                                              android:gravity="center_vertical"
                                              android:textSize="15dp"
                                              android:id="@+id/tv_dob"
                                              android:layout_toRightOf="@+id/tv_email"
                                              android:textColor="#000000"
                                              android:layout_marginLeft="10dp"
                                              android:layout_marginTop="10dp"/>
                                      </LinearLayout>
                                  
                                      <LinearLayout
                                          android:layout_width="match_parent"
                                          android:layout_height="wrap_content"
                                          android:orientation="horizontal">
                                  
                                          <TextView
                                              android:layout_width="100dp"
                                              android:layout_height="40dp"
                                              android:text="Location"
                                              android:gravity="center_vertical"
                                              android:textSize="15dp"
                                              android:textColor="#000000"
                                              android:layout_marginLeft="10dp"
                                              android:layout_marginTop="10dp"/>
                                  
                                          <TextView
                                              android:layout_width="wrap_content"
                                              android:layout_height="40dp"
                                              android:layout_below="@+id/tv_name"
                                              android:text="location"
                                              android:gravity="center_vertical"
                                              android:textSize="15dp"
                                              android:id="@+id/tv_location"
                                              android:textColor="#000000"
                                              android:layout_marginLeft="10dp"
                                              android:layout_marginTop="10dp"/>
                                      </LinearLayout>
                                  
                                  
                                      <LinearLayout
                                          android:layout_width="match_parent"
                                          android:background="#6585C8"
                                          android:id="@+id/ll_facebook"
                                          android:layout_marginLeft="10dp"
                                          android:layout_marginRight="10dp"
                                          android:layout_marginTop="40dp"
                                          android:layout_height="50dp">
                                  
                                          <ImageView
                                              android:layout_width="50dp"
                                              android:src="@drawable/facebook"
                                              android:id="@+id/iv_facebook"
                                              android:layout_height="50dp" />
                                  
                                          <TextView
                                              android:layout_width="wrap_content"
                                              android:layout_height="wrap_content"
                                              android:text="Login with Facebook"
                                              android:textSize="20dp"
                                              android:textColor="#FFFFFF"
                                              android:textStyle="bold"
                                              android:id="@+id/tv_facebook"
                                              android:layout_marginLeft="20dp"
                                              android:gravity="center"
                                              android:layout_gravity="center"
                                  
                                              />
                                  
                                      </LinearLayout>
                                  
                                      </LinearLayout>
                                  

                                  MainActivity.java

                                  package facebooklocation.facebooklocation;
                                  
                                  import android.content.Intent;
                                  import android.content.pm.PackageInfo;
                                  import android.content.pm.PackageManager;
                                  import android.content.pm.Signature;
                                  import android.support.v7.app.AppCompatActivity;
                                  import android.os.Bundle;
                                  import android.util.Base64;
                                  import android.util.Log;
                                  import android.view.View;
                                  import android.widget.ImageView;
                                  import android.widget.LinearLayout;
                                  import android.widget.TextView;
                                  import com.bumptech.glide.Glide;
                                  import com.facebook.AccessToken;
                                  import com.facebook.CallbackManager;
                                  import com.facebook.FacebookCallback;
                                  import com.facebook.FacebookException;
                                  import com.facebook.FacebookSdk;
                                  import com.facebook.GraphRequest;
                                  import com.facebook.GraphResponse;
                                  import com.facebook.HttpMethod;
                                  import com.facebook.login.LoginManager;
                                  import com.facebook.login.LoginResult;
                                  import org.json.JSONObject;
                                  import java.security.MessageDigest;
                                  import java.security.NoSuchAlgorithmException;
                                  import java.util.Arrays;
                                  
                                  public class MainActivity extends AppCompatActivity implements View.OnClickListener {
                                  
                                      CallbackManager callbackManager;
                                      ImageView iv_image, iv_facebook;
                                      TextView tv_name, tv_email, tv_dob, tv_location, tv_facebook;
                                      LinearLayout ll_facebook;
                                      String str_facebookname, str_facebookemail, str_facebookid, str_birthday, str_location;
                                      boolean boolean_login;
                                  
                                      @Override
                                      protected void onCreate(Bundle savedInstanceState) {
                                          super.onCreate(savedInstanceState);
                                          setContentView(R.layout.activity_main);
                                  
                                          init();
                                          getKeyHash();
                                          listener();
                                      }
                                  
                                  
                                      private void init() {
                                          iv_image = (ImageView) findViewById(R.id.iv_image);
                                          iv_facebook = (ImageView) findViewById(R.id.iv_facebook);
                                          tv_name = (TextView) findViewById(R.id.tv_name);
                                          tv_email = (TextView) findViewById(R.id.tv_email);
                                          tv_dob = (TextView) findViewById(R.id.tv_dob);
                                          tv_location = (TextView) findViewById(R.id.tv_location);
                                          tv_facebook = (TextView) findViewById(R.id.tv_facebook);
                                          ll_facebook = (LinearLayout) findViewById(R.id.ll_facebook);
                                          FacebookSdk.sdkInitialize(this.getApplicationContext());
                                      }
                                  
                                      private void listener() {
                                          tv_facebook.setOnClickListener(this);
                                          ll_facebook.setOnClickListener(this);
                                          iv_facebook.setOnClickListener(this);
                                  
                                      }
                                  
                                      private void facebookLogin() {
                                          callbackManager = CallbackManager.Factory.create();
                                          LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
                                              @Override
                                              public void onSuccess(LoginResult loginResult) {
                                                  Log.e("ONSUCCESS", "User ID: " + loginResult.getAccessToken().getUserId()
                                                          + "\n" + "Auth Token: " + loginResult.getAccessToken().getToken()
                                                  );
                                                  GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
                                                          new GraphRequest.GraphJSONObjectCallback() {
                                                              @Override
                                                              public void onCompleted(JSONObject object, GraphResponse response) {
                                                                  try {
                                  
                                                                      boolean_login = true;
                                                                      tv_facebook.setText("Logout from Facebook");
                                  
                                                                      Log.e("object", object.toString());
                                                                      str_facebookname = object.getString("name");
                                  
                                                                      try {
                                                                          str_facebookemail = object.getString("email");
                                                                      } catch (Exception e) {
                                                                          str_facebookemail = "";
                                                                          e.printStackTrace();
                                                                      }
                                  
                                                                      try {
                                                                          str_facebookid = object.getString("id");
                                                                      } catch (Exception e) {
                                                                          str_facebookid = "";
                                                                          e.printStackTrace();
                                  
                                                                      }
                                  
                                  
                                                                      try {
                                                                          str_birthday = object.getString("birthday");
                                                                      } catch (Exception e) {
                                                                          str_birthday = "";
                                                                          e.printStackTrace();
                                                                      }
                                  
                                                                      try {
                                                                          JSONObject jsonobject_location = object.getJSONObject("location");
                                                                          str_location = jsonobject_location.getString("name");
                                  
                                                                      } catch (Exception e) {
                                                                          str_location = "";
                                                                          e.printStackTrace();
                                                                      }
                                  
                                                                      fn_profilepic();
                                  
                                                                  } catch (Exception e) {
                                  
                                                                  }
                                                              }
                                                          });
                                                  Bundle parameters = new Bundle();
                                                  parameters.putString("fields", "id, name, email,gender,birthday,location");
                                  
                                                  request.setParameters(parameters);
                                                  request.executeAsync();
                                              }
                                  
                                              @Override
                                              public void onCancel() {
                                                  if (AccessToken.getCurrentAccessToken() == null) {
                                                      return; // already logged out
                                                  }
                                                  new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
                                                          .Callback() {
                                                      @Override
                                                      public void onCompleted(GraphResponse graphResponse) {
                                                          LoginManager.getInstance().logOut();
                                                          LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email"));
                                                          facebookLogin();
                                  
                                                      }
                                                  }).executeAsync();
                                  
                                  
                                              }
                                  
                                              @Override
                                              public void onError(FacebookException e) {
                                                  Log.e("ON ERROR", "Login attempt failed.");
                                  
                                  
                                                  AccessToken.setCurrentAccessToken(null);
                                                  LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday"));
                                              }
                                          });
                                      }
                                  
                                      @Override
                                      public void onActivityResult(int requestCode, int resultCode, Intent data) {
                                          super.onActivityResult(requestCode, resultCode, data);
                                  
                                          try {
                                              callbackManager.onActivityResult(requestCode, resultCode, data);
                                          } catch (Exception e) {
                                  
                                          }
                                  
                                      }
                                  
                                      private void getKeyHash() {
                                          // Add code to print out the key hash
                                          try {
                                              PackageInfo info = getPackageManager().getPackageInfo("facebooklocation.facebooklocation", PackageManager.GET_SIGNATURES);
                                              for (Signature signature : info.signatures) {
                                                  MessageDigest md = MessageDigest.getInstance("SHA");
                                                  md.update(signature.toByteArray());
                                                  Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
                                              }
                                          } catch (PackageManager.NameNotFoundException e) {
                                  
                                          } catch (NoSuchAlgorithmException e) {
                                  
                                          }
                                      }
                                  
                                      private void fn_profilepic() {
                                  
                                          Bundle params = new Bundle();
                                          params.putBoolean("redirect", false);
                                          params.putString("type", "large");
                                          new GraphRequest(
                                                  AccessToken.getCurrentAccessToken(),
                                                  "me/picture",
                                                  params,
                                                  HttpMethod.GET,
                                                  new GraphRequest.Callback() {
                                                      public void onCompleted(GraphResponse response) {
                                  
                                                          Log.e("Response 2", response + "");
                                  
                                                          try {
                                                              String str_facebookimage = (String) response.getJSONObject().getJSONObject("data").get("url");
                                                              Log.e("Picture", str_facebookimage);
                                  
                                                              Glide.with(MainActivity.this).load(str_facebookimage).skipMemoryCache(true).into(iv_image);
                                  
                                                          } catch (Exception e) {
                                                              e.printStackTrace();
                                                          }
                                  
                                                          tv_name.setText(str_facebookname);
                                                          tv_email.setText(str_facebookemail);
                                                          tv_dob.setText(str_birthday);
                                                          tv_location.setText(str_location);
                                  
                                                      }
                                                  }
                                          ).executeAsync();
                                      }
                                  
                                  
                                      @Override
                                      public void onClick(View view) {
                                  
                                          if (boolean_login) {
                                              boolean_login = false;
                                              LoginManager.getInstance().logOut();
                                              tv_location.setText("");
                                              tv_dob.setText("");
                                              tv_email.setText("");
                                              tv_name.setText("");
                                              Glide.with(MainActivity.this).load(R.drawable.profile).into(iv_image);
                                              tv_facebook.setText("Login with Facebook");
                                          } else {
                                              LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday,user_location"));
                                              facebookLogin();
                                          }
                                  
                                  
                                      }
                                  
                                  
                                      @Override
                                      protected void onDestroy() {
                                          super.onDestroy();
                                          LoginManager.getInstance().logOut();
                                      }
                                  }
                                  

                                  【讨论】:

                                  • 你能解释一下你的代码是如何回答这个问题的吗?
                                  【解决方案25】:
                                  new AsyncTask<String, Void, Bitmap>() {
                                          @Override
                                          protected Bitmap doInBackground(String... params) {
                                              Bitmap bitmap = null;
                                              try {
                                                  String imageURL = "https://graph.facebook.com/" + mFbUserId +"/picture?width=150&width=150";
                                                  URL imageURI = new URL(imageURL);
                                                  bitmap = BitmapFactory.decodeStream(imageURI.openConnection().getInputStream());
                                  
                                              } catch (Exception e) {
                                                  e.printStackTrace();
                                              }
                                              return bitmap;
                                          }
                                  
                                          @Override
                                          protected void onPostExecute(Bitmap bitmap) {
                                              super.onPostExecute(bitmap);
                                  
                                          }
                                  
                                          @Override
                                          protected void onPreExecute() {
                                              super.onPreExecute();
                                          }
                                      }.execute();
                                  

                                  【讨论】:

                                    【解决方案26】:

                                    注意:从 2018 年 3 月 26 日起,所有与手动链接相关的解决方案都不再起作用

                                    您应该关注official guide here

                                    private static String FACEBOOK_FIELD_PROFILE_IMAGE = "picture.type(large)";
                                        private static String FACEBOOK_FIELDS = "fields";
                                    
                                        private void getFacebookData() {
                                            GraphRequest request = GraphRequest.newMeRequest(
                                                    AccessToken.getCurrentAccessToken(),
                                                    (object, response) -> {
                                                        updateAvatar(getImageUrl(response));
                                                    });
                                            Bundle parameters = new Bundle();
                                            parameters.putString(FACEBOOK_FIELDS, FACEBOOK_FIELD_PROFILE_IMAGE);
                                            request.setParameters(parameters);
                                            request.executeAsync();
                                        }
                                    
                                        private static String FACEBOOK_FIELD_PICTURE = "picture";
                                        private static String FACEBOOK_FIELD_DATA = "data";
                                        private static String FACEBOOK_FIELD_URL = "url";
                                        private String getImageUrl(GraphResponse response) {
                                            String url = null;
                                            try {
                                                url = response.getJSONObject()
                                                        .getJSONObject(FACEBOOK_FIELD_PICTURE)
                                                        .getJSONObject(FACEBOOK_FIELD_DATA)
                                                        .getString(FACEBOOK_FIELD_URL);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                            return url;
                                        }
                                    

                                    【讨论】:

                                    • 谢谢,想知道为什么 facebook 个人资料图片突然从应用程序中消失了......
                                    【解决方案27】:

                                    由于问号,我的图表 api 无法正常工作

                                    如果您在图片后使用 1 个婴儿车,那就是

                                    picture&type=large
                                    

                                    对于两个参数,我们将使用问号

                                    picture?type=large&redirect=false
                                    

                                    希望对你有帮助!

                                    【讨论】:

                                      【解决方案28】:

                                      Facebook API 图表版本 3.2

                                      我已经做了这个实现:

                                      首先确保您在“onStart”或“onCreate”中添加了此权限 (这避免了 NetworkOnMainThreadException)。

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

                                      之后就可以使用下一个功能了:

                                      //Next lines are Strings used as params
                                      public static String FACEBOOK_FIELD_PROFILE_IMAGE = "picture.type(large)";
                                      public static String FACEBOOK_FIELDS = "fields";
                                      
                                      //A function that can be accessed from OnCreate (Or a similar function)
                                      private void setImageProfileFacebook(){
                                      
                                              AccessToken accessToken = AccessToken.getCurrentAccessToken();
                                              boolean isLoggedIn = accessToken != null && !accessToken.isExpired();            
                                      
                                              if(isLoggedIn) {
                                              //If the user is LoggedIn then continue
                                                  Bundle parameters = new Bundle();
                                                  parameters.putString(Util.FACEBOOK_FIELDS, Util.FACEBOOK_FIELD_PROFILE_IMAGE);
                                                  /* make the API call */
                                                  new GraphRequest(
                                                          AccessToken.getCurrentAccessToken(),
                                                          "me",
                                                          parameters,
                                                          HttpMethod.GET,
                                                          new GraphRequest.Callback() {
                                                              public void onCompleted(GraphResponse response) {
                                                                  /* handle the result */
                                                                  if (response != null) {
                                                                      try {
                                                                          JSONObject data = response.getJSONObject();
                                                                          //Log.w(TAG, "Data: " + response.toString());
                                      
                                                                          if (data.has("picture")) {
                                                                              boolean is_silhouette = data.getJSONObject("picture").getJSONObject("data").getBoolean("is_silhouette");
                                                                              if (!is_silhouette) {
                                                                              //Silhouette is used when the FB user has no upload any profile image
                                                                                  URL profilePicUrl = new URL(data.getJSONObject("picture").getJSONObject("data").getString("url"));
                                                                                  InputStream in = (InputStream) profilePicUrl.getContent();
                                                                                  Bitmap bitmap = BitmapFactory.decodeStream(in);
                                                                                  imageViewProfileFisio.setImageBitmap(bitmap);
                                                                              }
                                                                          }
                                      
                                                                      } catch (Exception e) {
                                                                          e.printStackTrace();
                                                                      }
                                                                  } else {
                                                                      Log.w(TAG, "Response null");
                                                                  }
                                                              }
                                                          }
                                                  ).executeAsync();
                                              }
                                          }
                                      

                                      我的示例是使用官方文档创建的: https://developers.facebook.com/docs/graph-api/reference/profile-picture-source/?locale=es_LA

                                      【讨论】:

                                        猜你喜欢
                                        • 2023-03-25
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2014-03-03
                                        • 1970-01-01
                                        • 1970-01-01
                                        相关资源
                                        最近更新 更多