要获取用户的 Facebook 个人资料图片,您必须使用 Facebook Android SDK V4(最新版本)。使用 Facebook Android SDK 获取图像后,您只需将 url 存储为字符串,并将其与您的 parseuser 相关联!要从用户设备获取图像,请使用带有 startactivityforresult 的意图。
确保您已配置 Facebook Android SDK,否则下面的所有说明对您来说几乎没有用处!
步骤 1. 使用 Facebook SDK 从 Facebook 获取个人资料图片
推荐。这应该在通过 Parse SDK 登录 Facebook 用户之后完成。
GraphJSONObjectCallback mCallback = new GraphJSONObjectCallback()
{
@Override
public void onCompleted(JSONObject mData, GraphResponse mResponse)
{
if(mResponse.getError() == null)
{
try
{
final JSONObject mPicture = mData.getJSONObject("picture");
final JSONObject mPictureData = mPicture.getJSONObject("data");
final boolean mSilhouette = mPictureData.getBoolean("is_silhouette");
**//this is the URL to the image that you want**
final String mImageUrl = mPictureData.getString("url");
}
catch (JSONException e)
{
//JSON Error, DEBUG
}
}
else
{
//Facebook GraphResponse error, DEBUG
}
}
};
Bundle mBundle = new Bundle();
mBundle.putString("fields", "picture");
GraphRequest mGetUserRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), mCallback);
mGetUserRequest.setParameters(mBundle);
//if running this on the MAIN THREAD then use .executeAsync()
mGetUserRequest.executeAndWait();
现在你应该有字符串 mImageUrl,所以你应该有 IMAGE。布尔值 mSilhuoette 让您知道是否正在使用默认的 silhuoette。查看 Facebook Android SDK 文档了解更多信息。
第 2 步:将 url 与用户关联
ParseUser mUser = ParseUser.getCurrentUser();
mUser.put("image", mImageUrl);
mUser.saveInBackground();
注意:您也可以自己下载图像并将其存储在 ParseFile 中。这取决于您打算如何在整个应用程序中使用此图像。
第 3 步:如果用户从他/她的设备上传图片,您可以使用带有 startactivity 的意图来允许用户选择图片。在 onActivityResult 中获取图像。将图像加载到位图中。一旦图像加载到位图中,然后将位图转换为解析文件并将该 ParseFile 与用户相关联,您就完成了!我建议为此使用 Picasso,并显示与 ParseUser 关联的图像 url。您可以通过 Google 搜索 Android Picasso 找到有关毕加索的更多信息。
当您准备好允许用户从设备中选择图像时:
Image mImagePickerIntent = new Intent();
mImagePickerIntent.setType("image/*");
mImagePickerIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent mMainIntent = Intent.createChooser(mImagePickerIntent, "Pick Image");
startActivityForResult(mMainIntent, 1);
在 onActivityResult 中使用这个
@Override
public void onActivityResult(int mRequestCode, int mResultCode, Intent mIntent)
{
super.onActivityResult(mRequestCode, mResultCode, mIntent);
if(mResultCode == Activity.RESULT_OK)
{
final Uri mImageUri = mIntent.getData();
//might be better to load bitmap with a Picasso Target (try/catch)
Bitmap mBitmap = Picasso.with(getActivity()).load(mImageUri).get();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
final byte[] mData = bos.toByteArray();
mBitmap.recycle();
final ParseFile mPhotoFile = new ParseFile("image.png", mData);
mPhotoFile.saveInBackground();
final ParseUser mUser = ParseUser.getCurrentUser();
mUser.put("imageFile", mPhotoFile);
mUser.saveInBackground();
}
}
上面的代码不是最终的!假设它代表了您为实现目标而必须做的工作的快照!为简洁起见省略了一些内容,例如 null 检查、try/catch 块等。