如何在Android

时间:2015-08-31 12:07:03

标签: android facebook image profile

我在android中使用Facebook sdk 4.4.0,我希望使用图形请求获取用户的当前个人资料图片。怎么做?

我见过人们使用

https://graph.facebook.com/me/picture?access_token=ACCESS_TOKEN

用于提取个人资料图片的API,但我无法想象如何从中提取个人资料图片。

9 个答案:

答案 0 :(得分:52)

您需要调用GraphRequest API来获取用户的所有详细信息,其中API还会提供当前个人资料图片的网址。

Bundle params = new Bundle();
params.putString("fields", "id,email,gender,cover,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());
                            mImageView.setBitmap(profilePic);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
}).executeAsync();

答案 1 :(得分:16)

从最后的sdk 4.5.0

开始
 String url;
 Bundle parametersPicture = new Bundle();
 parametersPicture.putString("fields", "picture.width(150).height(150)");

 GraphResponse lResponsePicture = new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/",
                        parametersPicture, null).executeAndWait();
 if (lResponsePicture != null && lResponsePicture.getError() == null &&
                            lResponsePicture.getJSONObject() != null) {
     url = lResponsePicture.getJSONObject().getJSONObject("picture")
                                .getJSONObject("data").getString("url");
 }

答案 2 :(得分:3)

你可以用两种不同的方式来做到这一点。

Way1:集成图形API支持 https://developers.facebook.com/docs/graph-api/reference/user/picture/

Way2:通过Get Call http:// graph.facebook.com/@facebook-Id}/picture?width=x&height=y

其中x和y可以是任何整数,例如100

答案 3 :(得分:3)

如果你想要真正的大图片,你必须要规范。至少一种尺寸的图片 - 例如

String profileImg = "https://graph.facebook.com/" + loginResult.getAccessToken().getUserId() + "/picture?type=large&width=1080";

此外,您可以指定两种尺寸(添加& height = some_val),但Facebook会裁剪此个人资料图片。

答案 4 :(得分:3)

从Facebook获取图片

Start

依赖

String image_url = "http://graph.facebook.com/" + Profile.getCurrentProfile().getId() + "/picture?type=large";
Glide.with(activity)
     .load(image_url)
     .into(imageView);

答案 5 :(得分:2)

protected void rajendra(LoginButton login_button){

    login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult login_result) {
            GraphRequest request = GraphRequest.newMeRequest(
                    login_result.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(
                                JSONObject object,
                                GraphResponse response) {

                            response.getError();

                            try {
                                if (android.os.Build.VERSION.SDK_INT > 9) {
                                    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                                    StrictMode.setThreadPolicy(policy);
                                    String profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");

                                    URL fb_url = new URL(profilePicUrl);//small | noraml | large
                                    HttpsURLConnection conn1 = (HttpsURLConnection) fb_url.openConnection();
                                    HttpsURLConnection.setFollowRedirects(true);
                                    conn1.setInstanceFollowRedirects(true);
                                    Bitmap fb_img = BitmapFactory.decodeStream(conn1.getInputStream());
                                    image.setImageBitmap(fb_img);
                                }
                            }catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,picture");
            request.setParameters(parameters);
            request.executeAsync();
        }

答案 6 :(得分:1)

uploadVideoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                                  uploadVideoButton.setEnabled(false);
                            uploadtoserver = new  UploadFileToServer();                                
                    uploadtoserver.execute(objVideoList.getImage_path());


}

private class UploadFileToServer extends AsyncTask<String, Integer, String> {

        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(AddVideoActivity.this);
            progressDialog.setMessage("Uploading Video...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setCancelable(true);
            progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                     if (uploadtoserver != null && uploadtoserver.getStatus() != AsyncTask.Status.FINISHED)
                          uploadtoserver.cancel(true);  
                }
            });

            progressDialog.show();

            super.onPreExecute();

        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            // progressBar.setProgress(progress[0]);
            // percentageTextView.setText(String.valueOf(progress[0]) + "%");
            if(isCancelled())
            {
            return ;
            }
            else
            {
            progressDialog.setProgress(progress[0]);
            if(progress[0] == 100)
            {
            progressDialog.setMessage("Validating video from server...");
            //progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            }
            }
        }

        @Override
        protected String doInBackground(String... params) {
            return uploadFile(params[0]);
        }

        @SuppressWarnings("deprecation")
        private String uploadFile(String filePath) {
            String responseString = null;

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(Constants.FILE_UPLOAD_URL);
            if(isCancelled())
            {
                publishProgress(CANCELLED);
            return(null);
            }
            try {
                AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                        new ProgressListener() {

                            @Override
                            public void transferred(long num) {


                                if(isCancelled())
                                {
                                publishProgress(CANCELLED);
                                return;
                                }
                                else
                                {
                                publishProgress( (int) ((num * 100) / totalSize));
                                //int value = (int) ((num * 100) / totalSize);
                                }


                                //publishProgress((int) ((num / (float) totalSize) * 100));
                            }
                        });

                File sourceFile = new File(filePath);

                // Adding file data to http body
                entity.addPart("video_file", new FileBody(sourceFile));

                String userId = new DevicePreferences().getString(
                        AddVideoActivity.this, Constants.PREF_USER_ID, "");
                entity.addPart("user_id", new StringBody(userId));
                entity.addPart("detail", new StringBody(descriptionEditText
                        .getText().toString()));
                entity.addPart("title", new StringBody(titletext.getText()
                        .toString()));
                entity.addPart("image_path", new StringBody(filePath));

                totalSize = entity.getContentLength();
                entity.addPart("video_size",
                        new StringBody(Long.toString(totalSize)));
                httppost.setEntity(entity);
                if(isCancelled())
                {
                    publishProgress(CANCELLED);
                return(null);
                }
                // Making server call
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity r_entity = response.getEntity();

                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    // Server response
                    responseString = EntityUtils.toString(r_entity);
                } else {
                    responseString = "Error occurred! Http Status Code: "
                            + statusCode;
                }

            } catch (ClientProtocolException e) {
                responseString = e.toString();
            } catch (IOException e) {
                responseString = e.toString();
            }

            return responseString;

        }
         @Override
            protected void onCancelled(String result) {
             if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            new AlertMessage(AddVideoActivity.this)
                .showAToast("Cancelled by user");   
            uploadVideoButton.setEnabled(true);

            super.onCancelled(result);
            }
        @Override
        protected void onPostExecute(String result) {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            //new AlertMessage(AddVideoActivity.this)
        //  .showAToast(result);
            if(!isCancelled())
            {
            Object json;
            try {
                json = new JSONTokener(result).nextValue();
                if (json instanceof JSONObject) {
                    JSONObject jsonObject = (JSONObject) json;
                    if (jsonObject.has("status")) {
                        if (jsonObject.getString("status").equalsIgnoreCase(
                                "ok")) {
                            objVideoList
                                    .setVideo_id(jsonObject.getString("id"));
                            showAlert("Uploaded Successfully.",
                                    percentageTextView, progressBar, true);
                        } else {
                            showAlert("Some error occured", percentageTextView,
                                    progressBar, false);
                        }
                    } else {
                        showAlert(result, percentageTextView, progressBar,
                                false);
                    }
                } else {
                    showAlert(result, percentageTextView, progressBar, false);
                }
            } catch (JSONException e) {
                showAlert(result, percentageTextView, progressBar, false);
            } finally {
                uploadVideoButton.setEnabled(true);
            }
            }
            super.onPostExecute(result);
        }

答案 7 :(得分:0)

只需拨打此网址:

graph.facebook.com/<facebook_user_id>/picture?type=large

类型可以是大的,正常的或小的。

另一种方法是使用ProfilePictureView

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

之后你可以在代码中设置这样的facebook id

profilePictureView.setProfileId(facebookUserId);

答案 8 :(得分:0)

脸书图片

https://graph.facebook.com/“+ facebookUid +”/ picture?height = 9999&amp; redirect = 0“

谷歌图片

String googleEmailName = googleEmail.substring(0,googleEmailName.indexOf(“@”))

http://picasaweb.google.com/data/entry/api/user/ “+ googleEmailName +”?ALT = JSON