我正在使用 Facebook 图形请求来检索好友列表。但是,如何创建一个函数并在调用 graphRequest.executeAsync()
完成后返回它?
private Map<String, String> getFacebookFriends(AccessToken accessToken, Profile profile) throws InterruptedException, ExecutionException {
final Map<String, String> friendsMap = new HashMap<>();
GraphRequest graphRequest = new GraphRequest(accessToken, "/me/friends", null, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
JSONObject jGraphObj = response.getJSONObject();
try {
JSONArray friendsData = jGraphObj.getJSONArray("data");
for (int i = 0; i < friendsData.length(); i++) {
JSONObject friend = friendsData.getJSONObject(i);
String friendId = friend.getString("id");
String friendName = friend.getString("name");
friendsMap.put(friendId, friendName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
List<GraphResponse> gResponseList = graphRequest.executeAsync().get();
return friendsMap;
}
我目前正在使用与this post中相同的技术。通过像 graphRequest.executeAsync().get();
那样调用它。但好像不起作用。
上面的函数将在 graphRequest
完成之前返回 friendsMap
。
如有任何建议,我们将不胜感激。
最佳答案
我通过使用 executeAndWait
而不是 executeAsync
函数来完成此工作。所以,这就是 final 的样子
public static Map<String, String> getFacebookFriends(AccessToken accessToken, Profile profile) throws InterruptedException, ExecutionException {
final Map<String, String> friendsMap = new HashMap<>();
GraphRequest.Callback gCallback = new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
JSONObject jGraphObj = response.getJSONObject();
try {
JSONArray friendsData = jGraphObj.getJSONArray("data");
for (int i = 0; i < friendsData.length(); i++) {
JSONObject friend = friendsData.getJSONObject(i);
String friendId = friend.getString("id");
String friendName = friend.getString("name");
friendsMap.put(friendId, friendName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
final GraphRequest graphRequest = new GraphRequest(accessToken, "/me/friends", null, HttpMethod.GET, gCallback);
// Run facebook graphRequest.
Thread t = new Thread(new Runnable() {
@Override
public void run() {
GraphResponse gResponse = graphRequest.executeAndWait();
}
});
t.start();
t.join();
return friendsMap;
}
关于java - Facebook API 如何等待 graphRequestexecuteAsync 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35905498/