Unity3D Facebook SDK for Android Integration - 5. 친구에게 앱 요청하기

 유니티3D 안드로이드 페이스북 친구 목록을 얻어와 친구 프로필 사진을 출력까지 해봤습니다. 이번에는 친구에게 같이 게임을 하기 위한 앱 요청을 처리해보겠습니다.

// 요청 다이얼로그 관련 변수 추가
private WebDialog dialog = null; private String dialogAction = null; private Bundle dialogParams = null;


public void inviteFriends_U(final String strMessage, final String strSuggestedFriends) {
runOnUiThread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
Bundle params = new Bundle();
params.putString("message", strMessage);
Log.d(LOG_TAG, "SuggestedFriends " + strSuggestedFriends);
if (strSuggestedFriends.isEmpty() == false) {
JSONArray jsonArr;
try {
jsonArr = new JSONArray(strSuggestedFriends);
String suggestedFriends[] = new String[jsonArr.length()];

for(int i = 0 ; i < jsonArr.length() ; i++) {
String strFbId = jsonArr.getJSONObject(i).getString("FacebookId");
suggestedFriends[i] = strFbId;
}
params.putString("suggestions", TextUtils.join(",", suggestedFriends));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
showDialogWithoutNotificationBar("apprequests", params);
}
});
}

 유니티3D에서 호출하는 안드로이드 소스입니다. strSuggestedFriends 유무에 따라 Bundle 파라메터를 다르게 설정합니다. 없으면 모든 친구 리스트를 보여주는 다이얼로그 창이 뜨고 몇몇 지정한 친구 리스트가 strSuggestedFriends에 있다면 해당 친구만 다이얼로그 창에 뜹니다.


private void showDialogWithoutNotificationBar(String action, Bundle params) {
// Create the dialog
dialog = new WebDialog.Builder(UnityPlayer.currentActivity, Session.getActiveSession(), action, params).setOnCompleteListener(
new WebDialog.OnCompleteListener() {

@Override
public void onComplete(Bundle values, FacebookException error) {

JSONObject jsonResult = new JSONObject();

try {
if (error != null) {
if (error instanceof FacebookOperationCanceledException) {
jsonResult.put("Result", "cancel");
} else {
//Log.d(LOG_TAG, "Request Failed. " + error.getMessage());
jsonResult.put("Result", "faile");
}
} else {
String requestId = values.getString("request");
if (requestId != null) {
JSONArray jsonArr = new JSONArray();
String strTo;
int i = 0;
do {
strTo = values.getString("to[" + i + "]");
if (strTo != null) {
JSONObject jsonTo = new JSONObject();
jsonTo.put("FacebookId", strTo);
jsonArr.put(jsonTo);
}
i++;
} while(strTo != null);
jsonResult.put("Result", "ok");
jsonResult.put("InviteFriends", jsonArr);
} else {
jsonResult.put("Result", "cancel");
}
}

dialog = null;
dialogAction = null;
dialogParams = null;
Log.d(LOG_TAG, "Invite Result " + jsonResult.toString());
UnityPlayer.UnitySendMessage("FacebookManager", "ResultInviteFriend_J", jsonResult.toString());

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).build();

// Hide the notification bar and resize to full screen
Window dialog_window = dialog.getWindow();
dialog_window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

// Store the dialog information in attributes
dialogAction = action;
dialogParams = params;

// Show the dialog
dialog.show();
}

 실제 요청 다이얼로그 창을 띄우고 onComplete 메소드에서 결과값과 요청 받은 친구 id를 정리해서 최종적으로 유니티3D에 넘겨줍니다.


public void InviteFriends(string strMessage, bool bSuggestedFriends)
{
StringBuilder sb = new StringBuilder();
JsonWriter writer = new JsonWriter(sb);
if(bSuggestedFriends == true)
{
writer.WriteArrayStart();

writer.WriteObjectStart();
writer.WritePropertyName("FacebookId");
writer.Write("695755709");
writer.WriteObjectEnd();

writer.WriteObjectStart();
writer.WritePropertyName("FacebookId");
writer.Write("685145706");
writer.WriteObjectEnd();

writer.WriteArrayEnd();

Debug.Log("bSuggestedFriends " + sb.ToString());
}

curActivity.Call("inviteFriends_U", strMessage, sb.ToString());
}

 이제 유니티3D FacebookManager 컴포넌트 소스입니다. LitJson의 JsonWriter에 페이스북 샘플에 있는 사람 2명을 추가했습니다.


public void ResultInviteFriend_J(string jsonResult)
{
JsonData jData = JsonMapper.ToObject(jsonResult);
//ok, cancel, faile
string strResult = jData["Result"].ToString();
if(strResult == "ok")
{
for (int i = 0 ; i < jData["InviteFriends"].Count ; i++)
{
string strFacebookId = jData["InviteFriends"][i]["FacebookId"].ToString();
}
}

SetLog(jsonResult);
}

 이건 요청 후 넘어온 결과를 처리하는 부분입니다. 게임에서는 결과값과 페이스북 ID를 확인해서 보상등을 한다던지 추가 처리를 하면 되겠죠.


fYpos += 50;
if (GUI.Button (new Rect(fXpos, fYpos, 100, 50), "Invite Friends") == true)
{
FacebookManager.GetInstance().InviteFriends("WestWoodForever's Facebook Android Invite Friend Test", false);
}

fYpos += 50;
if (GUI.Button (new Rect(fXpos, fYpos, 100, 50), "Suggested\nFriends") == true)
{
FacebookManager.GetInstance().InviteFriends("WestWoodForever's Facebook Android Suggested Invite Friend Test", true);
}

 마지막으로 TestGUI 컴포넌트입니다.


 iOS 페이스북 친구 요청때와 마찬가지로 페이스북 개발자 센터에서 앱의 네이티브 Android 앱 정보를 수정해야합니다. 개발중이신 Package Name과 메인 액티비티를 지정하고 저장합니다.

 요청 보내기 창을 눌러보면 이렇게 모든 친구가 리스트업이 됩니다.

 SuggestedFriends 만 했을 때는 위와 같이 해당 친구들만 리스트업이 되죠.

 요청을 받은 친구에게는 페이스북 안드로이드 앱에서 위와 같은 알림이 뜨고 해당 알림을 터치하면,

 구글 플레이가 실행되면서 앱이 있는 링크가 뜨거나 앱이 설치된 상태라면 앱이 실행됩니다.

댓글

이 블로그의 인기 게시물

'xxx.exe' 프로그램을 시작할 수 없습니다. 지정된 파일을 찾을 수 없습니다.

goorm IDE에서 node.js 프로젝트로 Hello World Simple Server 만들어 띄워보기

애드센스 수익을 웨스턴 유니온으로 수표대신 현금으로 지급 받아보자.