Skip to content

Instantly share code, notes, and snippets.

@bagobor
Created February 5, 2015 10:43
Show Gist options
  • Save bagobor/33de49905da1201ab853 to your computer and use it in GitHub Desktop.
Save bagobor/33de49905da1201ab853 to your computer and use it in GitHub Desktop.
2b19acb1ac85c20eb4d648619b7c5a9f9a6eef22
GoblinDefenders/Classes/Arena.cpp | 10 +-
GoblinDefenders/Classes/ArenaInfo.h | 1 +
GoblinDefenders/Classes/GameTypedef.h | 4 +-
GoblinDefenders/Classes/Helper.cpp | 9 +
GoblinDefenders/Classes/Helper.h | 3 +
GoblinDefenders/Classes/Item.cpp | 41 ++
GoblinDefenders/Classes/Item.h | 10 +
GoblinDefenders/Classes/JSONDataManager.cpp | 8 +
GoblinDefenders/Classes/Market.cpp | 30 +-
GoblinDefenders/Classes/ScoresManager.cpp | 14 +
GoblinDefenders/Classes/SelectLevel.cpp | 2 -
GoblinDefenders/Classes/SelectLevelMain.cpp | 7 +-
GoblinDefenders/Classes/Town.cpp | 2 +-
GoblinDefenders/Classes/UIBuyItem.cpp | 37 +-
GoblinDefenders/Classes/game.cpp | 11 +
GoblinDefenders/Classes/game.h | 3 +
GoblinDefenders/Classes/ios/HelperIOS.h | 2 +-
GoblinDefenders/Classes/ios/HelperIOS.mm | 13 +-
GoblinDefenders/Resources/Scenes/UI/Shop-ipad.json | 727 +++++++++++++++++++-
GoblinDefenders/Resources/Scenes/UI/Shop.json | 746 ++++++++++++++++++++-
GoblinDefenders/Resources/Xml/items.xml | 18 +-
GoblinDefenders/Resources/Xml/texts.xml | 8 +
GoblinDefenders/proj.android/AndroidManifest.xml | 2 +
.../GoblinDefenders2GP/GoblinDefenders.java | 107 +--
GoblinDefenders/proj.ios/AppController.mm | 2 +-
25 files changed, 1716 insertions(+), 101 deletions(-)
diff --combined GoblinDefenders/Classes/Arena.cpp
index d76a85d,7e1471b..63076fc
--- a/GoblinDefenders/Classes/Arena.cpp
+++ b/GoblinDefenders/Classes/Arena.cpp
@@@ -220,11 -220,6 +220,11 @@@ void Arena::parseParameters(xml_t xml
setReleaseEventCallback(gcTab, (SEL_TouchEvent)&Arena::onScoreTab);
setReleaseEventCallback(fbTab, (SEL_TouchEvent)&Arena::onScoreTab);
+ xml_t socialIconNode = xml_child(ratings, "SocialIcon");
+ sprintf(normalTexture, ezxml_attr(socialIconNode, "sprite"), SocialInterface::getInstance().buttonSuffix().c_str());
+ UIImageView* friendsIcon = (UIImageView*)getWidgetWithTag(xml_attr_int(socialIconNode, "tag", 0));
+ friendsIcon->loadTexture(normalTexture);
+
xml_t timeLabel = xml_child(widgets, "TimeLabel");
timeLabelTag = xml_attr_int(timeLabel, "tag", 0);
timeLabelTag2 = xml_attr_int(timeLabel, "tag2", 0);
@@@ -340,7 -335,8 +340,7 @@@ void Arena::loadFBpicture(int startPos
PictureInfo& info = it->second;
if(startPos < info.position < endPos && info.needLoad)
{
- int tag = atoi(it->second.socialId.c_str());
- SocialInterface::getInstance().GetPictureAsync(CCString::createWithFormat("%d", tag));
+ SocialInterface::getInstance().GetPictureAsync(CCString::create(it->second.socialId));
it->second.needLoad = false;
}
}
@@@ -925,7 -921,15 +925,15 @@@ void Arena::updateScroll(bool isFaceboo
UIImageView* crownImage = (UIImageView*)UIHelper::seekWidgetByTag(clone, crownTag);
if (crownImage)
- crownImage->setVisible(false);
+ {
+ int crowns = 0;
+
+ CCString* crownsStr = (CCString*)dict->objectForKey(ARENA_CROWN);
+ if (crownsStr)
+ crowns = crownsStr->intValue();
+
+ crownImage->setVisible(crowns > 0);
+ }
const ArrowInfo* aInfo = &arrowRatingMap[RATING_FLAT];
UIImageView* arrow = (UIImageView*)UIHelper::seekWidgetByTag(clone, aInfo->tag);
diff --combined GoblinDefenders/Classes/GameTypedef.h
index 8bab297,e9de140..63bb99c
--- a/GoblinDefenders/Classes/GameTypedef.h
+++ b/GoblinDefenders/Classes/GameTypedef.h
@@@ -342,9 -342,9 +342,9 @@@
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
- #define DEF_SPONSOR_PAY_AM_APP_ID "10031"
+ #define DEF_SPONSOR_PAY_AM_APP_ID "28782"
#define DEF_SPONSOR_PAY_ADVERT_APP_ID "A47096"
- #define DEF_SPONSOR_PAY_SECURITY_TOKET "e9517495761aad1fe98fdd4e12dbeb29"
+ #define DEF_SPONSOR_PAY_SECURITY_TOKET "81909dd9638816fea0ceed3536f23751"
#endif
@@@ -383,8 -383,6 +383,8 @@@ typedef enum typeDamage_t
#define LAST_FRAME INT_MAX
+#define FB_SOCIAL_REQUEST_ID "social_request_id"
+
#define SCORE_ID "id"
#define SCORE_FULL_ID "full_id"
#define SCORE_NAME "name"
diff --combined GoblinDefenders/Classes/Helper.cpp
index ac58cb6,54f4bf0..60576fe
--- a/GoblinDefenders/Classes/Helper.cpp
+++ b/GoblinDefenders/Classes/Helper.cpp
@@@ -280,9 -280,9 +280,9 @@@ bool isCloudConnected(
void writeStringToCloud(const char* str, const char* key)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
-#ifndef SOCIAL_PLATFORM_VK
- writeStringToCloud_IOS(str, key);
-#endif
+// #ifndef SOCIAL_PLATFORM_VK
+// writeStringToCloud_IOS(str, key);
+// #endif
#endif
}
@@@ -290,9 -290,9 +290,9 @@@ const char* getStringFromCloud(const ch
{
const char* str = NULL;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
-#ifndef SOCIAL_PLATFORM_VK
- str = getStringFromCloud_IOS(key);
-#endif
+// #ifndef SOCIAL_PLATFORM_VK
+// str = getStringFromCloud_IOS(key);
+// #endif
#endif
return str ? str : def;
@@@ -333,17 -333,6 +333,17 @@@ void showProfileDialog(const char* text
CCSendEvent(&e);
}
+const char* getSocialNetwork()
+{
+#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
+ return getSocialNetworkIOS();
+#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
+ return jgetSocialNetwork();
+#else
+ return "VK";
+#endif
+}
+
const char* getBundleID()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
@@@ -472,7 -461,7 +472,7 @@@ const char* getGCLeaderBoardTemplate()
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
return GCLeaderBoardTemplate();
#else
- return "com.redtrolls.gd2.arena%d";
+ return "arena%d";
#endif
}
@@@ -1140,8 -1129,8 +1140,8 @@@ void showChartboost(CCString* msg
void socialAuth()
{
-#ifdef GREE_ENABLED
- GreeDelegate::getInstance();
+#ifdef GOOGLE_PLAY_ENABLED
+ jsignIn();//GreeDelegate::getInstance();
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
if (!Profile::getInstance()->isAuth())
Profile::getInstance()->processAuth(CCString::create("goblin"));
@@@ -1168,8 -1157,6 +1168,8 @@@ bool requestGameCenterAuth(
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
return isGameCenterAuth();
+#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
+ return jisSignedIn();
#endif
return false;
}
@@@ -1917,5 -1904,14 +1917,14 @@@ bool isNewLeaderboard(
return xml_txt_bool(leaderBoard, false);
}
+
+ void showSponsorPay()
+ {
+ #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
+ showOfferWallIOS();
+ #elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
+ jshowOfferWall();
+ #endif
+ }
/////////////////////////////
diff --combined GoblinDefenders/Classes/Helper.h
index ba1c6b8,381f729..184d45a
--- a/GoblinDefenders/Classes/Helper.h
+++ b/GoblinDefenders/Classes/Helper.h
@@@ -211,7 -211,6 +211,7 @@@ typedef spx::refc_ptr<class ArenaInfo>
bool isDistributionBuildValue();
void openInbox();
+ const char* getSocialNetwork();
const char* getBundleID();
const char* getBuildNumber();
const char* getResourcesVersion();
@@@ -311,6 -310,9 +311,9 @@@
bool hideBag();
//static const char* notName[] = {"100", "101", "20%d%d", "300%d"};
+ //SponsorPay
+ void showSponsorPay();;
+
struct NotificationInfo
{
const char* name;
diff --combined GoblinDefenders/Classes/JSONDataManager.cpp
index c19458b,681176f..81389ac
--- a/GoblinDefenders/Classes/JSONDataManager.cpp
+++ b/GoblinDefenders/Classes/JSONDataManager.cpp
@@@ -34,6 -34,7 +34,7 @@@
#include "ArenaInfo.h"
#include "Stringss.h"
+ #include "game.h"
using namespace cocos2d;
using namespace extension;
@@@ -152,12 -153,14 +153,12 @@@ void JSONDataManager::profileRequest(
const char* username = Profile::getInstance()->getUserName()->getCString();
if (!strcmp(username, DEF_PLAYER_NAME))
{
-#ifdef SOCIAL_PLATFORM_VK
if (SocialInterface::getInstance().IsLoggedIn())
{
unsigned long long accountID = SocialInterface::getInstance().getID();
sprintf(url, URL_PROFILE_URL_TEMPLATE, getGameServerUrl(), SocialInterface::getInstance().buttonSuffix().c_str(), accountID);
}
else
-#endif
{
Event e = CCCreateEvent(E_PROFILE_DOWNLOADED, this, NULL);
CCSendEvent(&e);
@@@ -553,6 -556,9 +554,9 @@@ void JSONDataManager::profileSend(
if (isNewLeaderboard())
{
+ bool crown = Game::getInstance()->isHaveArenaCrown();
+ data.AddMember(ARENA_CROWN, crown, root.GetAllocator());
+
Value arena(kObjectType);
auto aInfo = getCurrentArenaInfo();
@@@ -1046,6 -1052,10 +1050,10 @@@ void JSONDataManager::applyServerData(
if (arena.HasMember("kills"))
aInfo->setMobsKill(arena["kills"].GetInt());
}
+ if (data.HasMember(ARENA_CROWN))
+ {
+ Game::getInstance()->setArenaCrown(data[ARENA_CROWN].GetBool());
+ }
}
else
{
diff --combined GoblinDefenders/Classes/SelectLevelMain.cpp
index 64c4814,2a04917..ce022a8
--- a/GoblinDefenders/Classes/SelectLevelMain.cpp
+++ b/GoblinDefenders/Classes/SelectLevelMain.cpp
@@@ -65,8 -65,6 +65,8 @@@ SelectLevelMain::SelectLevelMain(Screen
questCompletedAction = NULL;
scroll_ = NULL;
menuButton = NULL;
+ googleBtn = NULL;
+ googleBtnAction = NULL;
soundOff = NULL;
musicOff = NULL;
scollLastPos_ = CCPointZero;
@@@ -132,15 -130,6 +132,15 @@@ void SelectLevelMain::parseParameters(x
int starsPanelTag = xml_attr_int(ezxml_child(labels, "Stars"), "panel", 0);
starsPanel = UIWidgetPtr(getWidgetWithTag(starsPanelTag));
+ xml_t google = ezxml_child(resources, "GooglePlay");
+ int googleTag = xml_attr_int(google, "tag", 0);
+ googleBtn = (UIButton*)getWidgetWithTag(googleTag);
+ setReleaseEventCallback(googleTag, (SEL_TouchEvent)&SelectLevelMain::onGoogle);
+ int leaderboardTag = xml_attr_int(google, "leaderboard", 0);
+ int achievesTag = xml_attr_int(google, "achieves", 0);
+ setReleaseEventCallback(leaderboardTag, (SEL_TouchEvent)&SelectLevelMain::onLeaderboard);
+ setReleaseEventCallback(achievesTag, (SEL_TouchEvent)&SelectLevelMain::onAchieves);
+
xml_t buy_node = ezxml_child(resources, "Buy");
createResourcesBuy(buy_node);
@@@ -187,24 -176,7 +187,24 @@@
sprintf(buff, ezxml_attr(fbLogInOut, "normal"), SocialInterface::getInstance().buttonSuffix().c_str());
fbLoginLogout->loadTextures(buff, buff, buff);
-
+ if (SocialInterface::getInstance().getSocialNetworkType() == SN_FACEBOOK)
+ {
+ float loginSpace = fbLoginLogout->getPosition().y - fbNameBack->getPosition().y;
+ int fbPosTag = xml_attr_int(fbLogInOut, "posTag", 0);
+ UIWidget* tempBtn = getWidgetWithTag(fbPosTag);
+ fbNameBack->setPosition(tempBtn->getPosition());
+ fbLoginLogout->setPosition(ccp(tempBtn->getPosition().x, tempBtn->getPosition().y + loginSpace));
+
+ xml_t groupsNode = xml_child(xml_child(XmlDB::getInstance().getDoc(xmlGame), "SocialNetwork"), "GroupsVK");
+
+ for(xml_t xmlChild=xml_child_first(groupsNode); xmlChild; xmlChild=xml_ordered(xmlChild))
+ {
+ int tag = xml_attr_int(xmlChild, "id", 0);
+ UIButton* btn = (UIButton*)getWidgetWithTag(tag);
+ btn->setTouchEnabled(false);
+ btn->setVisible(false);
+ }
+ }
oldLogoutPos = fbLoginLogout->getPosition();
if (SocialInterface::getInstance().IsLoggedIn())
@@@ -252,9 -224,9 +252,9 @@@
CCARRAY_FOREACH(achieves, obj)
{
Achieve* achieve = (Achieve*)obj;
- if (achieve->isAvailable() && !achieve->isPerformed())
+ if (achieve->isAvailable() && !achieve->isPerformed() && achieve->isVisible())
flag->setVisible(true);
- if (achieve->isPerformed() && !achieve->isRewarded())
+ if (achieve->isPerformed() && !achieve->isRewarded() && achieve->isVisible())
{
SoundControl::getInstance()->playEffectWithTag(FX_QUEST_COMPLETED_NOTIFICATION);
questAction = playAction(m_actionsJson.c_str(), questRewardAnim);
@@@ -304,42 -276,6 +304,42 @@@
scheduleOnce(schedule_selector(SelectLevelMain::hideAlert), 0.01f);
}
+void SelectLevelMain::onLeaderboard(CCObject* sender, TouchEventType type)
+{
+ if (type != TOUCH_EVENT_ENDED)
+ return;
+
+ if (!Profile::getInstance()->isAuth())
+ {
+#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
+ jsignIn();
+#endif
+ return;
+ }
+
+#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
+ jshowLeaderboard("");
+#endif
+}
+
+void SelectLevelMain::onAchieves(CCObject* sender, TouchEventType type)
+{
+ if (type != TOUCH_EVENT_ENDED)
+ return;
+
+ if (!Profile::getInstance()->isAuth())
+ {
+#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
+ jsignIn();
+#endif
+ return;
+ }
+
+#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
+ jshowAchievements();
+#endif
+}
+
void SelectLevelMain::checkGroups()
{
joinButton->setTouchEnabled(false);
@@@ -410,9 -346,6 +410,9 @@@ void SelectLevelMain::onExit(
questDoneAnim = NULL;
menuAnimation = NULL;
+ googleBtn = NULL;
+ googleBtnAction = NULL;
+
ResourcesUI::onExit();
CCRemoveAllEventListener(this);
@@@ -452,6 -385,10 +452,10 @@@ xml_t SelectLevelMain::getResourcesUIXm
void SelectLevelMain::onEnter()
{
+ #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
+ jqueryGear();
+ #endif
+
JSONDataManager::getInstance().checkIfGameNeedsUpdate();
if (SocialInterface::getInstance().IsLoggedIn())
@@@ -624,7 -561,7 +628,7 @@@
cocos2d::extension::sendEvent(TRIGGEREVENT_ENTERSCENE);
CCDirector::sharedDirector()->getTouchDispatcher()->setDispatchEvents(true);
- CCDirector::sharedDirector()->getTouchDispatcher()->setSkipFrames(2);
+ CCDirector::sharedDirector()->getTouchDispatcher()->setSkipFrames(100);
CCDirector::sharedDirector()->getTouchDispatcher()->disableMultiTouch(true);
int megaGunCount = ud_get_int(MEGA_GUN, 0);
@@@ -645,6 -582,7 +649,7 @@@
void SelectLevelMain::update(float dt)
{
+ CCDirector::sharedDirector()->getTouchDispatcher()->setSkipFrames(0);
timeToCheckLogin -= dt;
ResourcesUI::update(dt);
if (timeToCheckLogin <= 0)
@@@ -875,22 -813,6 +880,22 @@@ void SelectLevelMain::questCallback(CCO
ScreenManager::getInstance().runScreen(quest);
}
+void SelectLevelMain::onGoogle(CCObject* sender, TouchEventType type)
+{
+ if (type != TOUCH_EVENT_ENDED)
+ return;
+
+ if(googleBtnAction && !googleBtnAction->isDone())
+ return;
+
+ if (googleBtn->isBright())
+ googleBtnAction = playAction(m_actionsJson.c_str(), "gb_buttons_show");
+ else
+ googleBtnAction = playAction(m_actionsJson.c_str(), "gb_buttons_hide");
+
+ googleBtn->setBright(!googleBtn->isBright());
+}
+
void SelectLevelMain::onMenu(CCObject* sender, TouchEventType type)
{
if (type != TOUCH_EVENT_ENDED || (menuAnimation && !menuAnimation->isDone()))
@@@ -1042,12 -964,12 +1047,12 @@@ bool SelectLevelMain::processEvent(Even
CCARRAY_FOREACH(achieves, obj)
{
Achieve* achieve = (Achieve*)obj;
- if (achieve->isAvailable() && !achieve->isPerformed())
+ if (achieve->isAvailable() && !achieve->isPerformed() && achieve->isVisible())
{
flag->setVisible(true);
available++;
}
- if (achieve->isPerformed() && !achieve->isRewarded())
+ if (achieve->isPerformed() && !achieve->isRewarded() && achieve->isVisible())
{
questAction = playAction(m_actionsJson.c_str(), questRewardAnim);
questAction->setLoop(true);
@@@ -1068,7 -990,7 +1073,7 @@@
else if (evnt->type == E_OPEN_ACHIEVE)
{
Achieve* achieve = (Achieve*)evnt->sender;
- if (!achieve->isShown())
+ if (!achieve->isShown() && achieve->isVisible())
completedQuests.push_back(achieve);
questAction = playAction(m_actionsJson.c_str(), questRewardAnim);
questAction->setLoop(true);
diff --combined GoblinDefenders/Classes/game.cpp
index 819beb7,4bac4e5..a11d903
--- a/GoblinDefenders/Classes/game.cpp
+++ b/GoblinDefenders/Classes/game.cpp
@@@ -114,11 -114,9 +114,11 @@@ void Game::loadGameOptions(xml_t root
// FACEBOOK
- xml_t nodeFB = xml_child(root, "Facebook");
+ xml_t nodeFB = xml_child(root, "SocialNetwork");
loginOnStartScreen_ = xml_attr_bool(nodeFB, "loginOnStartScreen", false);
- xml_t links = xml_child(nodeFB, "Links");
+ char buff[32];
+ sprintf(buff, "Links%s", getSocialNetwork());
+ xml_t links = xml_child(nodeFB, buff);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
storeLink_ = ezxml_attr(links, "appStore");
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
@@@ -126,10 -124,10 +126,10 @@@
#else
storeLink_ = "";
#endif
- countRandStory_ = xml_attr_int(links, "countRandStory", 8);
+
+ countRandStory_ = xml_attr_int(nodeFB, "countRandStory", 8);
fbGroup_ = ezxml_attr(links, "groupID");
- std::string pictureAttrName = "picture" + SocialInterface::getInstance().getSuffix();
- fbPicture_ = ezxml_attr(links, pictureAttrName.c_str());
+ fbPicture_ = ezxml_attr(links, "picture");
xml_t nodeRewards = xml_child(nodeFB, "Rewards");
fbRewards_[FB_LIKE] = xml_attr_int(nodeRewards, "like", 2);
@@@ -235,7 -233,7 +235,7 @@@ Game::~Game(
CC_SAFE_RELEASE(levelsInfo_);
}
-const char* Game::facebookPictureLink()
+std::string Game::facebookPictureLink()
{
return fbPicture_;
}
@@@ -243,7 -241,7 +243,7 @@@
const char* Game::facebookGroupLink()
{
static char buff[512];
- sprintf(buff, "http://www.facebook.com/%s", fbGroup_);
+ sprintf(buff, "http://www.facebook.com/%s", fbGroup_.c_str());
const char* link = buff;
return link;
}
@@@ -254,7 -252,12 +254,7 @@@ bool Game::canInvite(
return enableSocialInvites && friendsLimit > invites;
}
-const char* Game::facebookGroupID()
-{
- return fbGroup_;
-}
-
-const char* Game::storeLink()
+std::string Game::storeLink()
{
return storeLink_;
}
@@@ -693,4 -696,15 +693,15 @@@ int Game::leftTimeForSpawnSpirit(bool c
int Game::getCountRandStory() const
{
return countRandStory_;
+ }
+
+ void Game::setArenaCrown(bool isCrown)
+ {
+ ud_set_bool(isCrown, ARENA_CROWN);
+ ud_serialize_without_send();
+ }
+
+ bool Game::isHaveArenaCrown()
+ {
+ return ud_get_bool(ARENA_CROWN, false);
}
diff --combined GoblinDefenders/Classes/game.h
index 5237f85,e8040f8..34e6765
--- a/GoblinDefenders/Classes/game.h
+++ b/GoblinDefenders/Classes/game.h
@@@ -86,7 -86,6 +86,7 @@@ class Game : public CCObject, public Si
int lastGlobalMapTag_;
int heroID_;
bool showID_;
+ std::string fbGroup_;
std::map<std::string, std::string> resourceIconPath;
@@@ -108,8 -107,9 +108,8 @@@
void loadGameOptions(xml_t root);
- const char* fbGroup_;
- const char* fbPicture_;
- const char* storeLink_;
+ std::string fbPicture_;
+ std::string storeLink_;
int fbRewards_[FB_COUNT];
int countRandStory_;
@@@ -157,7 -157,6 +157,7 @@@ public
game_mode_t gameMode();
void setGameMode(game_mode_t gm);
void reorderGameObj(GameObj* child, int zOrder);
+ const char* facebookGroupLink();
void addPlayerMoney(money_t cash);
void subPlayerMoney(money_t cash);
@@@ -170,8 -169,10 +170,8 @@@
void showTowersGrid();
void hideTowersGrid();
- const char* facebookPictureLink();
- const char* facebookGroupLink();
- const char* facebookGroupID();
- const char* storeLink();
+ std::string facebookPictureLink();
+ std::string storeLink();
int getFacebookRewards(int action);
void addGameObj(TowerPtr obj, int z);
@@@ -206,6 -207,9 +206,9 @@@
int timeLeftForReqestsQuota(bool update = true);
int getCountRandStory() const;
+
+ void setArenaCrown(bool isCrown);
+ bool isHaveArenaCrown();
};
#endif // __HELLOWORLD_SCENE_H__
diff --combined GoblinDefenders/Classes/ios/HelperIOS.h
index 77a56fe,731a7bd..44a4139
--- a/GoblinDefenders/Classes/ios/HelperIOS.h
+++ b/GoblinDefenders/Classes/ios/HelperIOS.h
@@@ -28,12 -28,10 +28,12 @@@ extern "C"
void reloadStoreIOS();
void loadingPlayerWithId(CCString* uId);
-
+
+ const char* getSocialNetworkIOS();
+
bool needsUpdateIOS();
void updateIOS();
-
+
const char* bundleID();
const char* buildNumber();
const char* GCLeaderBoardTemplate();
@@@ -50,7 -48,7 +50,7 @@@
void showMoreGames();
void showSubscribe();
void showMailIOS();
- void showOfferWall();
+ void showOfferWallIOS();
void showChartboostIOS(CCString* msg);
void showLeaderboard();
diff --combined GoblinDefenders/Classes/ios/HelperIOS.mm
index fc7f137,b1a9a83..e010e0c
--- a/GoblinDefenders/Classes/ios/HelperIOS.mm
+++ b/GoblinDefenders/Classes/ios/HelperIOS.mm
@@@ -91,14 -91,14 +91,14 @@@ void modulesLogin(
[AlawarStatistics startSession];
[[Chartboost sharedChartboost] startSession];
- //[SponsorPaySDK startForAppId:DEF_SPONSOR_PAY_AM_APP_ID
- // userId:[MyUDID getUDID]
- // securityToken:DEF_SPONSOR_PAY_SECURITY_TOKET];
+ [SponsorPaySDK startForAppId:DEF_SPONSOR_PAY_AM_APP_ID
+ userId:[MyUDID getUDID]
+ securityToken:DEF_SPONSOR_PAY_SECURITY_TOKET];
[[InAppPurchaseMng instance] loadStore];
setPurchaseListenerEnabledIOS(true);
- //[[VirtualCurrencyConnector instance] autoSendRequest];
+ [[VirtualCurrencyConnector instance] autoSendRequest];
[[PurchaseWrapper sharedWrapeer] loadProducts];
#ifdef TESTFLIGHT_ENABLED
@@@ -183,12 -183,6 +183,12 @@@ void ShowAlert(int event, const char* t
[alert release];
}
+const char* getSocialNetworkIOS()
+{
+ NSString* sn = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"SocialNetwork"];
+ return [sn UTF8String];
+}
+
const char* bundleID()
{
NSString* bundleID = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
@@@ -232,11 -226,12 +232,12 @@@ void showMailIOS(
[[AlawarController instance] showMail];
}
- void showOfferWall()
+ void showOfferWallIOS()
{
- //[[SPController instance] showOfferWall];
+ [[SPController instance] showOfferWall];
}
+
void showChartboostIOS(CCString* msg)
{
[[Chartboost sharedChartboost] showInterstitial:[NSString stringWithUTF8String:msg->getCString()]];
diff --combined GoblinDefenders/Resources/Xml/texts.xml
index 45f08ad,6b0092b..9109ba3
--- a/GoblinDefenders/Resources/Xml/texts.xml
+++ b/GoblinDefenders/Resources/Xml/texts.xml
@@@ -4746,6 -4746,14 +4746,14 @@@
<de>Erweckt deinen Helden sofort wieder zum Leben</de>
<es>Resucita instantГЎneamente a tu hГ©roe</es>
</key>
+ <key id="item2112_desc">
+ <en>Get crystals for free!</en>
+ <ru>Получи кристаллы бесплатно!</ru>
+ </key>
+ <key id="item2112_name">
+ <en>Free Crystals</en>
+ <ru>Бесплатные кристаллы</ru>
+ </key>
<key id="item2107_name">
<en>Spirit Tank</en>
<ru>Хранилище Духа</ru>
@@@ -5755,7 -5763,7 +5763,7 @@@
<es>ВЎLlГ©vate %s, amigo! ВЎA por ellos!</es>
</key>
<key id="requestGiftTitle">
- <en>Your friend is in danger! Send him or her the %s!</en>
+ <en>Send %s to your friend!</en>
<ru>Твой друг в беде! Отправь ему %s!</ru>
<fr>Votre ami est en dangerВ ! Envoyez-lui le %sВ !</fr>
<it>Uno dei tuoi amici ha bisogno di aiuto! Inviagli %s!</it>
@@@ -6605,12 -6613,4 +6613,12 @@@ Je besser dein Kampf ist, desto besser
<en>Failed connect to server. Try again later.</en>
<ru>Не удалось связаться с сервером. Попробуйте позже.</ru>
</key>
+ <key id="loginFB">
+ <en>Login with Facebook</en>
+ <ru>Войти через Facebook</ru>
+ <fr>Connexion avec Facebook</fr>
+ <it>Accedi con Facebook</it>
+ <de>Anmeldung mit Facebook</de>
+ <es>Iniciar sesiГіn con Facebook</es>
+ </key>
</texts>
diff --combined GoblinDefenders/proj.android/AndroidManifest.xml
index 165654e,a20f61d..a8450bd
--- a/GoblinDefenders/proj.android/AndroidManifest.xml
+++ b/GoblinDefenders/proj.android/AndroidManifest.xml
@@@ -1,8 -1,8 +1,8 @@@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.ShpagaGames.GoblinDefenders2VK"
- android:versionCode="141270"
- android:versionName="1.5.215"
+ package="com.ShpagaGames.GoblinDefenders2GP"
+ android:versionCode="141000"
+ android:versionName="1.6.215"
android:installLocation="preferExternal">
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
@@@ -35,15 -35,11 +35,15 @@@
android:largeHeap="true"
android:hardwareAccelerated="true">
- <service android:name="com.ShpagaGames.GoblinDefenders2VK.SampleDownloaderService" />
- <receiver android:name="com.ShpagaGames.GoblinDefenders2VK.SampleAlarmReceiver" />
- <receiver android:name=".AlarmReceiver" />
+ <service android:name="com.ShpagaGames.GoblinDefenders2GP.SampleDownloaderService" />
+ <receiver android:name="com.ShpagaGames.GoblinDefenders2GP.SampleAlarmReceiver" />
+ <receiver android:name="com.ShpagaGames.GoblinDefenders2GP.AlarmReceiver" />
- <activity android:name=".SplashActivity"
+ <meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id" />
+ <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
+ <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" />
+
+ <!--activity android:name="com.ShpagaGames.GoblinDefenders2GP.SplashActivity"
android:label="@string/app_name"
android:screenOrientation="sensorLandscape"
android:theme="@style/OtherActivitiesTheme"
@@@ -59,16 -55,16 +59,16 @@@
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
- </activity>
+ </activity-->
- <activity android:name=".GoblinDefenders"
+ <activity android:name="com.ShpagaGames.GoblinDefenders2GP.GoblinDefenders"
android:label="@string/app_name"
android:screenOrientation="sensorLandscape"
android:theme="@style/ImmersiveStickyTheme"
android:configChanges="locale|keyboardHidden|orientation|screenSize"
android:hardwareAccelerated="true"
android:launchMode="singleTask">
- <!--intent-filter>
+ <intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
@@@ -77,12 -73,10 +77,12 @@@
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT" />
- </intent-filter-->
- </activity>
+ </intent-filter>
+ </activity>
- <activity android:name="com.vk.sdk.VKOpenAuthActivity" android:theme="@style/OtherActivitiesTheme"/>
+ <activity android:name="com.facebook.LoginActivity"
+ android:theme="@style/OtherActivitiesTheme"
+ android:label="@string/app_name" />
<!-- in-app billing service -->
<!-- service android:name="com.modernalchemists.mass.android.BillingService" /-->
@@@ -99,7 -93,7 +99,7 @@@
<activity android:name="com.flurry.android.CatalogActivity"
android:theme="@android:style/Theme.Translucent" >
<intent-filter>
- <action android:name="com.ShpagaGames.GoblinDefenders2VK.catalogactivity"/>
+ <action android:name="com.ShpagaGames.GoblinDefenders2GP.catalogactivity"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
@@@ -111,12 -105,13 +111,14 @@@
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
- <category android:name="com.ShpagaGames.GoblinDefenders2VK"/>
+ <category android:name="com.ShpagaGames.GoblinDefenders2GP"/>
</intent-filter>
</receiver>
+
+ <activity android:name="com.sponsorpay.publisher.ofw.SPOfferWallActivity" android:configChanges="orientation"/>
<meta-data android:name="com.crashlytics.ApiKey" android:value="78844782d67853008abd1787c8f40a63f4c8889a"/>
+ <meta-data android:name="SocialNetwork" android:value="FB" />
<meta-data android:name="isDistributionBuild" android:value="false" />
<meta-data android:name="alawar_statwrapper_mode" android:value="test"/>
<meta-data android:name="alawar_stat_app_id" android:value="goblins2vk_android" />
@@@ -143,13 -138,13 +145,13 @@@
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
- <uses-permission android:name="com.ShpagaGames.GoblinDefenders2VK.permission.C2D_MESSAGE"/>
+ <uses-permission android:name="com.ShpagaGames.GoblinDefenders2GP.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="com.android.vending.CHECK_LICENSE" />
- <permission android:name="com.ShpagaGames.GoblinDefenders2VK.permission.C2D_MESSAGE" android:protectionLevel="signature"/>
- <uses-permission android:name="com.ShpagaGames.GoblinDefenders2VK.permission.C2D_MESSAGE"/>
- <permission android:name="com.ShpagaGames.GoblinDefenders2VK.permission.PAYMENT_BROADCAST_PERMISSION" android:protectionLevel="signature"/>
- <uses-permission android:name="com.ShpagaGames.GoblinDefenders2VK.permission.PAYMENT_BROADCAST_PERMISSION"/>
+ <permission android:name="com.ShpagaGames.GoblinDefenders2GP.permission.C2D_MESSAGE" android:protectionLevel="signature"/>
+ <uses-permission android:name="com.ShpagaGames.GoblinDefenders2GP.permission.C2D_MESSAGE"/>
+ <permission android:name="com.ShpagaGames.GoblinDefenders2GP.permission.PAYMENT_BROADCAST_PERMISSION" android:protectionLevel="signature"/>
+ <uses-permission android:name="com.ShpagaGames.GoblinDefenders2GP.permission.PAYMENT_BROADCAST_PERMISSION"/>
</manifest>
diff --combined GoblinDefenders/proj.android/src/com/ShpagaGames/GoblinDefenders2GP/GoblinDefenders.java
index ceb9a8f,0000000..d319f7c
mode 100644,000000..100644
--- a/GoblinDefenders/proj.android/src/com/ShpagaGames/GoblinDefenders2GP/GoblinDefenders.java
+++ b/GoblinDefenders/proj.android/src/com/ShpagaGames/GoblinDefenders2GP/GoblinDefenders.java
@@@ -1,2286 -1,0 +1,2295 @@@
+/****************************************************************************
+Copyright (c) 2010-2012 cocos2d-x.org
+
+http://www.cocos2d-x.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+ ****************************************************************************/
+package com.ShpagaGames.GoblinDefenders2GP;
+
+import com.chartboost.sdk.ChartboostDelegate;
+import com.crashlytics.android.Crashlytics;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.math.BigInteger;
+import java.net.URL;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Scanner;
+
+import org.fmod.*;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.protocol.HTTP;
+import org.cocos2dx.lib.Cocos2dxActivity;
+import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
+import org.cocos2dx.lib.Cocos2dxHelper;
+
+import android.accounts.Account;
+import android.accounts.AccountManager;
+import android.annotation.SuppressLint;
+import android.annotation.TargetApi;
+import android.app.AlarmManager;
+import android.app.AlertDialog;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.support.v4.app.DialogFragment;
+import android.app.ProgressDialog;
+import android.content.ComponentName;
+//import android.app.NativeActivity;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnDismissListener;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.Signature;
+import android.content.res.Configuration;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.CountDownTimer;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.Message;
+import android.os.RemoteException;
+import android.text.Html;
+import android.text.TextUtils;
+import android.util.Base64;
+//import android.provider.SyncStateContract.Helpers;
+import android.util.Log;
+import android.view.GestureDetector;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.WindowManager;
+import android.widget.Toast;
+
+import com.ShpagaGames.GoblinDefenders2GP.R;
+import com.alawar.biglib.utils.chartboost.ChartboostHelper;
++import com.alawar.biglib.utils.sponsorpay.SponsorPayHelper;
++import com.alawar.biglib.utils.sponsorpay.SponsorPayHelper.RewardListener;
+import com.alawar.f2p.common.BackgroundExecutor;
+import com.alawar.f2p.common.ErrorCodes;
+import com.alawar.f2p.data.RequestData;
+import com.alawar.f2p.data.RequestData.Method;
+import com.alawar.f2p.network.LibException;
+import com.alawar.f2p.network.RequestProcessor;
+import com.alawar.statwrapper.AlaStatWrapper;
+import com.alawar.subscriber.SubscriberActivity;
+
+import com.android.util.IabException;
+import com.android.util.IabHelper;
+import com.android.util.IabResult;
+import com.android.util.Inventory;
+import com.android.util.Purchase;
+import com.android.util.SkuDetails;
+import com.android.vending.billing.IInAppBillingService;
+
+import com.easyndk.classes.AndroidNDKHelper;
+import com.facebook.AppEventsLogger;
+import com.facebook.FacebookException;
+import com.facebook.FacebookOperationCanceledException;
+import com.facebook.HttpMethod;
+import com.facebook.Request;
+import com.facebook.Response;
+import com.facebook.Session;
+import com.facebook.Session.StatusCallback;
+import com.facebook.SessionLoginBehavior;
+import com.facebook.SessionState;
+import com.facebook.TokenCachingStrategy;
+import com.facebook.UiLifecycleHelper;
+import com.facebook.model.GraphObject;
+import com.facebook.model.GraphUser;
+import com.facebook.widget.FacebookDialog;
+import com.facebook.widget.WebDialog;
+import com.facebook.widget.WebDialog.OnCompleteListener;
+import com.flurry.android.FlurryAgent;
+import com.google.android.gms.auth.GoogleAuthUtil;
+import com.google.android.gms.common.AccountPicker;
+
- public class GoblinDefenders extends GooglePlayActivity {
-
++public class GoblinDefenders extends Cocos2dxActivity implements RewardListener {
+ private static String hash;
+ public static Context appContext;
+ private static GoblinDefenders me;
+ static IabHelper mHelper;
+ private IInAppBillingService mService;
+ private UiLifecycleHelper uiHelper;
+ private static ProgressDialog progressDialog;
+ private static int inAppTag;
+ private static String inAppEvent;
+ private static String inAppID;
+ private static String md5Fingerprint = "";
+ private static String inAppCurrencyCode = "";
+ private static boolean inAppConsumable;
+ private static String flyerMsg;
+ private static int reward;
+ private static String currentLocale;
+ private static boolean asyncOperationActive;
+ private static View mDecorView;
+ private static final int INITIAL_HIDE_DELAY = 300;
+ private static int usersProcessed = 0;
+ private static boolean isDistributionBuild;
+ private static boolean testPurchase = false;
+ private static Inventory mInventory = null;
+ private static Map<Integer, Integer> notifications = new HashMap<Integer, Integer>();
+ private static StatusCallback lastCallback;
+
+ private static boolean getFriendInviteActive = false;
+ private static boolean getFriendNotInviteActive = false;
+
+ public static final int GOOGLE_LOGIN_ACTIVITY_RESULT = 123;
+
+ ServiceConnection mServiceConn = new ServiceConnection() {
+ @Override
+ public void onServiceDisconnected(ComponentName name) {
+ mService = null;
+ }
+
+ @Override
+ public void onServiceConnected(ComponentName name, IBinder service) {
+ mService = IInAppBillingService.Stub.asInterface(service);
+ }
+ };
+
+ private static final String[] consumableInApps = {
- "com.shpagagames.goblindefenders2vk.50gems.1usd",
- "com.shpagagames.goblindefenders2vk.150gems.2usd",
- "com.shpagagames.goblindefenders2vk.400gems.3usd",
- "com.shpagagames.goblindefenders2vk.1000gems.5usd",
- "com.shpagagames.goblindefenders2vk.newbiepack",
- "com.shpagagames.goblindefenders2vk.itemsonsale2.9.99usd",
- "com.shpagagames.goblindefenders2vk.itemsonsale3.9.99usd",
- "com.shpagagames.goblindefenders2vk.itemsonsale4.9.99usd",
- "com.shpagagames.goblindefenders2vk.200gems.3usd",
- "com.shpagagames.goblindefenders2vk.700gems.7usd",
- "com.shpagagames.goblindefenders2vk.1500gems.10usd",
- "com.shpagagames.goblindefenders2vk.4000gems.20usd",
- "com.shpagagames.goblindefenders2vk.12000gems.50usd"
++ "com.shpagagames.goblindefenders2gp.50gems.1usd",
++ "com.shpagagames.goblindefenders2gp.150gems.2usd",
++ "com.shpagagames.goblindefenders2gp.400gems.3usd",
++ "com.shpagagames.goblindefenders2gp.1000gems.5usd",
++ "com.shpagagames.goblindefenders2gp.newbiepack",
++ "com.shpagagames.goblindefenders2gp.itemsonsale2.9.99usd",
++ "com.shpagagames.goblindefenders2gp.itemsonsale3.9.99usd",
++ "com.shpagagames.goblindefenders2gp.itemsonsale4.9.99usd",
++ "com.shpagagames.goblindefenders2gp.200gems.3usd",
++ "com.shpagagames.goblindefenders2gp.700gems.7usd",
++ "com.shpagagames.goblindefenders2gp.1500gems.10usd",
++ "com.shpagagames.goblindefenders2gp.4000gems.20usd",
++ "com.shpagagames.goblindefenders2gp.12000gems.50usd"
+ };
+
+ private static final String[] nonConsumableInApps = {
- "com.shpagagames.goblindefenders2vk.ammunition",
- "com.shpagagames.goblindefenders2vk.dropincrease",
- "com.shpagagames.goblindefenders2vk.fox",
- "com.shpagagames.goblindefenders2vk.sbm",
- "com.shpagagames.goblindefenders2vk.necrom"
++ "com.shpagagames.goblindefenders2gp.ammunition",
++ "com.shpagagames.goblindefenders2gp.dropincrease",
++ "com.shpagagames.goblindefenders2gp.fox",
++ "com.shpagagames.goblindefenders2gp.sbm",
++ "com.shpagagames.goblindefenders2gp.necrom"
+ };
+
+ private static final List<String> basicPermissionsFB = Arrays.asList(
+ "public_profile",
+ "user_friends",
+ "user_likes"
+ );
+
+ private static final List<String> publishPermissionsFB = Arrays.asList(
+ "publish_actions"
+ );
+
+ private static final List<String> testAccounts = Arrays.asList(
+ "alagametest@gmail.com",
+ "maximko.online@gmail.com",
+ "goblingun1@gmail.com",
+ "goblingun3@gmail.com",
+ "goblingun4@gmail.com",
+ "goblingun6@gmail.com",
+ "goblingun7@gmail.com",
+ "goblingun8@gmail.com"
+
+ );
+
+ private static String supportEmail = "goblinsupport@alawar.com";
+
+ private static final String VK_APP_ID = "4459663";
+
+ private native static void pauseGame();
+ private native static void resumeGame();
+ private native static void reviewResult(int result);
+ private native static void addGear(int gems);
+ private native static void addGearOfferwall(int gems);
+ private native static void completeTransaction(String productID, int result);
+ private native static void sendEvent(int id);
+ private native static void localeChanged();
+ private native static void autoSerialize();
+ private native static void syncProgress();
+ private native static void exitGame();
+ private native static void setInAppPrice(String sku, String price);
+ private native static void priceQueryOver(boolean success);
+ private native static void requestCleanProfile();
+ private native static void openInbox();
+
+ private static void completeTransactionOnGLThread(final String productID,
+ final int result) {
+ me.runOnGLThread(new Runnable() {
+ @Override
+ public void run() {
+ completeTransaction(productID, result);
+ }
+ });
+ }
+
+ public String getAppID()
+ {
+ String appID = getString(R.string.facebook_app_id);
+ return appID;
+ }
+
+ public void createSession()
+ {
+ Session session = new Session.Builder(this).setApplicationId(getAppID()).setTokenCachingStrategy(null).build();
+ Session.setActiveSession(session);
+ }
+
+ StatusCallback statusCallback = new Session.StatusCallback() {
+ @Override
+ public void call(Session session, SessionState status, Exception exception) {
+ if (status == SessionState.CLOSED_LOGIN_FAILED ||
+ status == SessionState.CLOSED)
+ {
+ Session.getActiveSession().closeAndClearTokenInformation();
+ Session.getActiveSession().removeCallback(statusCallback);
+ Session.setActiveSession(null);
+ AndroidNDKHelper.SendMessageWithParameters("onLoginError", null);
+ }
+ else if (status == SessionState.OPENED ||
+ status == SessionState.OPENED_TOKEN_UPDATED)
+ {
+ Session.getActiveSession().removeCallback(statusCallback);
+ GetUserInfoFacebook();
+ Request.newGraphPathRequest(session, "/me/permissions", new Request.Callback() {
+ @Override
+ public void onCompleted(Response response) {
+ JSONObject object = response.getGraphObject().getInnerJSONObject();
+ if(object != null){
+ try {
+ JSONArray granted = new JSONArray();
+ JSONArray permissionsFromServer = object.getJSONArray("data");
+ for (int i = 0; i < permissionsFromServer.length(); ++i)
+ {
+ JSONObject dict = (JSONObject) permissionsFromServer.get(i);
+ String status = dict.getString("status");
+ if (status.equals("declined"))
+ continue;
+
+ String permission = dict.getString("permission");
+ granted.put(permission);
+ }
+ JSONObject json = new JSONObject();
+ json.put("granted", granted);
+ AndroidNDKHelper.SendMessageWithParameters("onGetPermissions", json);
+ } catch (JSONException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ else{
+ // error
+ }
+ }
+ }).executeAsync();
+ }
+ }
+ };
+
+ StatusCallback reloginCallback = new Session.StatusCallback() {
+ @Override
+ public void call(final Session session, SessionState status, Exception exception) {
+ if (status == SessionState.OPENED || status == SessionState.OPENED_TOKEN_UPDATED)
+ {
+ Session.getActiveSession().removeCallback(reloginCallback);
+ Request.newGraphPathRequest(session, "/me/permissions", new Request.Callback() {
+
+ @Override
+ public void onCompleted(Response response) {
+ try {
+ JSONObject object = response.getGraphObject().getInnerJSONObject();
+ if(object != null){
+ JSONArray granted = new JSONArray();
+ List<String> readPermissions = new ArrayList<String>();
+ final List<String> publishPermissions = new ArrayList<String>();
+ JSONArray permissionsFromServer = object.getJSONArray("data");
+ for (int i = 0; i < permissionsFromServer.length(); ++i)
+ {
+ JSONObject dict = (JSONObject) permissionsFromServer.get(i);
+ String status = dict.getString("status");
+ if (status.equals("declined"))
+ continue;
+
+ String permission = dict.getString("permission");
+ granted.put(permission);
+ if (permission.startsWith("publish"))
+ publishPermissions.add(permission);
+ else
+ readPermissions.add(permission);
+ }
+ JSONObject json = new JSONObject();
+ json.put("granted", granted);
+ AndroidNDKHelper.SendMessageWithParameters("onGetPermissions", json);
+
+ final StatusCallback gotPublishPermissionsCallback = new Session.StatusCallback() {
+ @Override
+ public void call(final Session session, SessionState status, Exception exception) {
+ if (status == SessionState.OPENED || status == SessionState.OPENED_TOKEN_UPDATED)
+ {
+ Session.getActiveSession().removeCallback(lastCallback);
+ GetUserInfoFacebook();
+ }
+ }
+ };
+
+ final StatusCallback gotReadPermissionsCallback = new Session.StatusCallback() {
+ @Override
+ public void call(final Session session, SessionState status, Exception exception) {
+ if (status == SessionState.OPENED || status == SessionState.OPENED_TOKEN_UPDATED)
+ {
+ if (publishPermissions.isEmpty())
+ return;
+
+ Session.getActiveSession().removeCallback(lastCallback);
+ lastCallback = gotPublishPermissionsCallback;
+ session.requestNewPublishPermissions(new Session.NewPermissionsRequest(me, publishPermissions).setCallback(gotPublishPermissionsCallback).setLoginBehavior(SessionLoginBehavior.SSO_ONLY));
+ }
+ }
+ };
+
+ lastCallback = gotReadPermissionsCallback;
+ session.requestNewReadPermissions(new Session.NewPermissionsRequest(me, readPermissions).setCallback(lastCallback).setLoginBehavior(SessionLoginBehavior.SSO_ONLY));
+ //Session.openActiveSession(me, false, permissions, reloginCallback);
+
+ }
+ else{
+ me.showDialog(me.getString(R.string.error), me.getString(R.string.check_internets));
+ }
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ me.showDialog(me.getString(R.string.error), me.getString(R.string.check_internets));
+ }
+ }
+ }).executeAsync();
+ }
+ }
+ };
+
+ public void LoginFB(JSONObject prms) {
+ Log.d("FB", "login");
+
+ if (Session.getActiveSession() == null)
+ {
+ createSession();
+ }
+ if (!Session.getActiveSession().isOpened())
+ {
+ Session.openActiveSession(this, true, basicPermissionsFB, statusCallback);
+ }
+ }
+
+ public static void GetUserInfoFacebook()
+ {
+ Request.newMeRequest(Session.getActiveSession(), new Request.GraphUserCallback() {
+
+ @Override
+ public void onCompleted(GraphUser user, Response response) {
+ // TODO Auto-generated method stub
+ if (response != null && user != null)
+ {
+ String userID = user.getId();
+ JSONObject json = new JSONObject();
+ try {
+ json.put("id", user.getId());
+ json.put("name", user.getName());
+ json.put("userSex", "0");
+ } catch (JSONException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ AndroidNDKHelper.SendMessageWithParameters("onLoginSuccessful", json);
+ AndroidNDKHelper.SendMessageWithParameters("onGotUserInfo", json);
+
+ String photo = "http://graph.facebook.com/" + user.getId() + "/picture?width=168&height=168";
+ if (photo != null) {
+ try {
+ JSONObject params = new JSONObject();
+ params.put("id", "profile" + user.getId());
+ me.DeletePictureVK(params);
+ } catch (JSONException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ PictureDownloader downloader = new PictureDownloader(
+ me, 1000);
+ downloader.download("profile" + userID, photo,
+ "onProfilePictureReady");
+ }
+ }
+ else
+ me.showDialog(me.getString(R.string.error), me.getString(R.string.check_internets));
+ }
+ }).executeAsync();
+ }
+
+ public void GetUserInfoFB(JSONObject prms) {
+
+ }
+
+ public void CheckIfLoggedInFB(JSONObject prms) throws JSONException {
+ String id = prms.getString("id");
+ if (Session.getActiveSession() != null && id.isEmpty())
+ {
+ Session.getActiveSession().closeAndClearTokenInformation();
+ Session.setActiveSession(null);
+ return;
+ }
+ List<String> permissions = Arrays.asList("public_profile");
+ Session.openActiveSession(this, false, permissions, reloginCallback);
+ }
+
+ public void LogoutFB(JSONObject prms) {
+ Log.d("FB", "logout");
+ Session.getActiveSession().closeAndClearTokenInformation();
+ Session.setActiveSession(null);
+ }
+
+ public void RequestPermissionFB(final JSONObject prms) throws JSONException {
+ Session session = Session.getActiveSession();
+ if (session == null || !session.isOpened())
+ return;
+
+ String permission = prms.getString("permission");
+ if (permission.startsWith("publish"))
+ {
+ final StatusCallback gotPublishPermissionsCallback = new Session.StatusCallback() {
+ @Override
+ public void call(final Session session, SessionState status, Exception exception) {
+ if (status == SessionState.OPENED || status == SessionState.OPENED_TOKEN_UPDATED)
+ {
+ Session.getActiveSession().removeCallback(lastCallback);
+ AndroidNDKHelper.SendMessageWithParameters("onGetPermission", prms);
+ }
+ }
+ };
+
+ lastCallback = gotPublishPermissionsCallback;
+ session.requestNewPublishPermissions(new Session.NewPermissionsRequest(me, permission).setCallback(lastCallback));
+ }
+ else
+ {
+ final StatusCallback gotReadPermissionsCallback = new Session.StatusCallback() {
+ @Override
+ public void call(final Session session, SessionState status, Exception exception) {
+ if (status == SessionState.OPENED || status == SessionState.OPENED_TOKEN_UPDATED)
+ {
+ Session.getActiveSession().removeCallback(lastCallback);
+ AndroidNDKHelper.SendMessageWithParameters("onGetPermission", prms);
+ }
+ }
+ };
+
+ lastCallback = gotReadPermissionsCallback;
+ session.requestNewReadPermissions(new Session.NewPermissionsRequest(me, permission).setCallback(lastCallback));
+ }
+ }
+
+ public void PostStoryFB(final JSONObject prms) throws JSONException {
+ String title = prms.getString("title");
+ String link = prms.getString("store");
+ String photo = prms.getString("picture");
+ String message = prms.getString("message");
+ String gameName = prms.getString("game");
+
+ if (FacebookDialog.canPresentShareDialog(getApplicationContext(), FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
+ FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this)
+ .setLink(link)
+ .setName(title)
+ .setCaption(gameName)
+ .setPicture(photo)
+ .setDescription(message)
+ .build();
+ uiHelper.trackPendingDialogCall(shareDialog.present());
+ }
+ else
+ {
+ Bundle params = new Bundle();
+ params.putString("link", link);
+ params.putString("name", title);
+ params.putString("caption", gameName);
+ params.putString("picture", photo);
+ params.putString("description", message);
+
+ WebDialog feedDialog = (
+ new WebDialog.FeedDialogBuilder(this,
+ Session.getActiveSession(),
+ params))
+ .setOnCompleteListener(new OnCompleteListener() {
+
+ @Override
+ public void onComplete(Bundle values,
+ FacebookException error) {
+ if (error == null) {
+ // When the story is posted, echo the success
+ // and the post Id.
+ final String postId = values.getString("post_id");
+ if (postId != null) {
+ Log.d("FB", "Posted story, id: " + postId);
+ AndroidNDKHelper.SendMessageWithParameters("onStoryPublished", null);
+ } else {
+ // User clicked the Cancel button
+ Log.d("FB", "User canceled story publishing.");
+ AndroidNDKHelper.SendMessageWithParameters("onShareDialogClosed", null);
+ }
+ } else if (error instanceof FacebookOperationCanceledException) {
+ // User clicked the "x" button
+ Log.d("FB", "User canceled story publishing.");
+ AndroidNDKHelper.SendMessageWithParameters("onShareDialogClosed", null);
+ } else {
+ // Generic, ex: network error
+ Log.d("FB", "Error posting story");
+ AndroidNDKHelper.SendMessageWithParameters("onShareDialogClosed", null);
+ }
+ }
+ })
+ .build();
+ feedDialog.show();
+ }
+ }
+
+ public void GetLikeFB(final JSONObject prms) throws JSONException {
+ if (Session.getActiveSession() == null)
+ return;
+
+ String id = prms.getString("group");
+ new Request(
+ Session.getActiveSession(),
+ "/me/likes/" + id,
+ null,
+ HttpMethod.GET,
+ new Request.Callback() {
+ public void onCompleted(Response response) {
+ try {
+ if(response == null || response.getGraphObject() == null)
+ return;
+ JSONObject json = response.getGraphObject().getInnerJSONObject();
+ JSONArray data = json.getJSONArray("data");
+ if (data.length() > 0) {
+ Log.d("FB", "FB page liked!");
+ AndroidNDKHelper.SendMessageWithParameters("onPageLiked", null);
+ }
+ else
+ Log.d("FB", "FB page not liked!");
+ } catch (JSONException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+ ).executeAsync();
+ }
+
+ public void PostScoreFB(JSONObject prms) throws JSONException {
+ if (Session.getActiveSession() == null)
+ return;
+
+ String score = prms.getString("score");
+ Bundle params = new Bundle();
+ params.putString("score", score);
+ /* make the API call */
+ new Request(
+ Session.getActiveSession(),
+ "/me/scores",
+ params,
+ HttpMethod.POST,
+ new Request.Callback() {
+ public void onCompleted(Response response) {
+ /* handle the result */
+ }
+ }
+ ).executeAsync();
+ }
+
+ public void GetFriendsFB(final JSONObject prms) throws JSONException {
+ Log.d("FB", "get friends");
+ final int invite = Integer.parseInt(prms.getString("invite"));
+ final boolean isInvite = invite > 0;
+ if ((getFriendNotInviteActive == true && !isInvite) || isInvite || Session.getActiveSession() == null)
+ return;
+
+ getFriendNotInviteActive = true;
+
+ new Request(
+ Session.getActiveSession(),
+ "/me/friends",
+ null,
+ HttpMethod.GET,
+ new Request.Callback() {
+ public void onCompleted(Response response) {
+ try {
+ JSONObject jsonFriends = new JSONObject();
+ JSONObject json = response.getGraphObject().getInnerJSONObject();
+ JSONArray data = json.getJSONArray("data");
+ for (int i = 0; i < data.length(); ++i) {
+ JSONObject user = (JSONObject)data.get(i);
+ String id = user.getString("id");
+ String name = user.getString("name");
+ jsonFriends.put(id, name);
+ }
+ jsonFriends.put("invite", prms.getString("invite"));
+ AndroidNDKHelper.SendMessageWithParameters("onGotFriends", jsonFriends);
+ getFriendNotInviteActive = false;
+
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ me.showDialog(me.getString(R.string.error), me.getString(R.string.check_internets));
+ }
+ }
+ }
+ ).executeAsync();
+ }
+
+ public void GetUserPictureFB(JSONObject prms) throws JSONException {
+ String id = prms.getString("uid");
+ PictureManager.addPicture(id, me);
+ }
+
+ public void DeletePictureFB(JSONObject prms) throws JSONException {
+ DeletePictureVK(prms);
+ }
+
+ public void CancelAllDownloadsFB(JSONObject prms) {
+ Log.d("FB", "dialog closed - stop download");
+ PictureManager.clear();
+ }
+
+ public void RequestFriendFB(JSONObject prms) throws JSONException {
+ String title = prms.getString("title");
+ String message = prms.getString("message");
+
+ Bundle params = new Bundle();
+ params.putString("title", title);
+ params.putString("message", message);
+
+ WebDialog requestDialog = (
+ new WebDialog.RequestsDialogBuilder(this,
+ Session.getActiveSession(),
+ params))
+ .setOnCompleteListener(new OnCompleteListener() {
+
+ @Override
+ public void onComplete(Bundle values, FacebookException error) {
+ if (error == null) {
+ // When the story is posted, echo the success
+ // and the post Id.
+ final String postId = values.getString("request");
+ if (postId != null) {
+ Log.d("FB", "Request Sent: " + postId);
+
+ } else {
+ // User clicked the Cancel button
+ Log.d("FB", "User canceled request.");
+
+ }
+ } else if (error instanceof FacebookOperationCanceledException) {
+ // User clicked the "x" button
+ Log.d("FB", "User canceled request.");
+
+ } else {
+ // Generic, ex: network error
+ Log.d("FB", "Error sending request.");
+
+ }
+ }
+ })
+ .build();
+ requestDialog.show();
+
+ }
+
+ public void SendRequestWithDataFB(final JSONObject prms) throws JSONException {
+ JSONArray selectedFriends = (JSONArray) prms.get("friends");
+ String title = (String) prms.get("title");
+ String message = (String) prms.get("message");
+ String name = (String) prms.get("nameBonus");
+ String isSendGift = (String) prms.get("isSendGift");
+
+ if (isSendGift.equals("-1"))
+ {
+ OnRequestSent(prms);
+ return;
+ }
+
+ String type = "request";
+ if (isSendGift.equals("2")) //invite
+ type = "invite";
+
+ Bundle data = new Bundle();
+ data.putString("nameBonus", name);
+ data.putString("isSendGift", isSendGift);
+
+ String userIds = selectedFriends.join(",");
+ userIds = userIds.replace("\"", "");
+
+ Bundle params = new Bundle();
+ params.putString("title", title);
+ params.putString("message", message);
+ params.putBundle("data", data);
+ params.putString("to", userIds);
+
+ String enableSocialRequests = (String) prms.get("enableSocialRequests");
+ if (enableSocialRequests.equals("1")) {
+
+ WebDialog requestDialog = (
+ new WebDialog.RequestsDialogBuilder(this,
+ Session.getActiveSession(),
+ params))
+ .setOnCompleteListener(new OnCompleteListener() {
+
+ @Override
+ public void onComplete(Bundle values, FacebookException error) {
+ if (error == null) {
+ // When the story is posted, echo the success
+ // and the post Id.
+ try
+ {
+ final String postId = values.getString("request");
+ if (postId != null) {
+ Log.d("FB", "Request Sent: " + postId);
+ prms.put("fb_request_id", postId);
+ OnRequestSent(prms);
+ } else {
+ // User clicked the Cancel button
+ Log.d("FB", "User canceled request.");
+ AndroidNDKHelper.SendMessageWithParameters("onRequestCanceled", null);
+ }
+ }
+ catch (JSONException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ AndroidNDKHelper.SendMessageWithParameters("onRequestCanceled", null);
+ }
+
+ } else if (error instanceof FacebookOperationCanceledException) {
+ // User clicked the "x" button
+ Log.d("FB", "User canceled request.");
+ AndroidNDKHelper.SendMessageWithParameters("onRequestCanceled", null);
+
+ } else {
+ // Generic, ex: network error
+ Log.d("FB", "Error sending request.");
+ AndroidNDKHelper.SendMessageWithParameters("onRequestCanceled", null);
+ }
+ }
+ })
+ .build();
+ requestDialog.show();
+ }
+ else {
+ Log.d("fb", "successful request is successful");
+ OnRequestSent(prms);
+ }
+ }
+
+ public void GetFriendsInfoFB(JSONObject prms) throws JSONException {
+ JSONArray userIdsArr = (JSONArray) prms.get("friends");
+ final String userIds = userIdsArr.join(",").replace("\"", "");
+
+ new Request(
+ Session.getActiveSession(),
+ "/me/friends",
+ null,
+ HttpMethod.GET,
+ new Request.Callback() {
+ public void onCompleted(Response response) {
+ try {
+ JSONArray usersInfoArr = new JSONArray();
+ JSONObject json = response.getGraphObject().getInnerJSONObject();
+ JSONArray data = json.getJSONArray("data");
+ for (int i = 0; i < data.length(); ++i) {
+ JSONObject user = (JSONObject)data.get(i);
+ String id = user.getString("id");
+ if (!userIds.contains(id))
+ continue;
+
+ JSONObject dict = new JSONObject();
+ String name = user.getString("name");
+ dict.put("name", name);
+ dict.put("uid", id);
+ dict.put("userSex", "0");
+ usersInfoArr.put(dict);
+ }
+
+ JSONObject usersInfoDict = new JSONObject();
+ usersInfoDict.put("usersInfo", usersInfoArr);
+ AndroidNDKHelper.SendMessageWithParameters("onGetUsersInfo", usersInfoDict);
+
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ me.showDialog(me.getString(R.string.error), me.getString(R.string.check_internets));
+ }
+ }
+ }
+ ).executeAsync();
+ }
+
+ public void DeleteRequestFB(final JSONObject prms) throws JSONException
+ {
+ String id = prms.getString("fbid");
+
+ new Request(
+ Session.getActiveSession(),
+ id,
+ null,
+ HttpMethod.DELETE,
+ new Request.Callback() {
+ public void onCompleted(Response response) {
+ AndroidNDKHelper.SendMessageWithParameters("onRequestDeleted", prms);
+ }
+ }
+ ).executeAsync();
+ }
+
+ public void GetUserPictureVK(JSONObject prms) throws JSONException {
+ String id = prms.getString("uid");
+ PictureManager.addPicture(id, me);
+ }
+
+ public void DeletePictureVK(JSONObject prms) throws JSONException {
+ String id = prms.getString("id");
+
+ if (id == null || me == null)
+ return;
+
+ try {
+ File file = new File(me.getExternalFilesDir("").getAbsolutePath()
+ + "/" + id);
+ JSONObject params = new JSONObject();
+ params.put("file", file.getAbsolutePath());
+ AndroidNDKHelper.SendMessageWithParameters("deletePicFromCache",
+ params);
+ if (file.exists())
+ file.delete();
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ public void CancelAllDownloadsVK(JSONObject prms) {
+ Log.d("VK", "dialog closed - stop download");
+ PictureManager.clear();
+ }
+
+ public void OnRequestSent(JSONObject prms)
+ {
+ try {
+ JSONArray selectedFriends = (JSONArray) prms.get("friends");
+ String name = (String) prms.get("nameBonus");
+ String isSendGift = (String) prms.get("isSendGift");
+ boolean put = prms.has("put");
+ boolean fb = prms.has("fb_request_id");
+
+ JSONObject jsonFriends = new JSONObject();
+ jsonFriends.put("selectedFriends", selectedFriends);
+ jsonFriends.put("bonus", name);
+ jsonFriends.put("isSendGift", isSendGift);
+ if (fb)
+ jsonFriends.put("fb_request_id", (String) prms.get("fb_request_id"));
+ if (put)
+ jsonFriends.put("put", "put");
+
+ String type = "request";
+ if (isSendGift.equals("2")) //invite
+ type = "invite";
+
+ jsonFriends.put("type", type);
+
+ AndroidNDKHelper.SendMessageWithParameters("onRequestSent", jsonFriends);
+
+ } catch (JSONException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ Crashlytics.start(this);
+
+ loadAlaStatWrapperConfigFromTestFile();
+
+ DeviceUuidFactory dev = new DeviceUuidFactory(this);
+ int uuid = dev.getDeviceUuid().hashCode();
+ hash = Integer.toString(uuid);// Secure.getString(getApplicationContext().getContentResolver(),
+ // Secure.ANDROID_ID);
+ Log.d("Device UUID", hash);
+ appContext = getApplicationContext();
+ me = this;
+
+ Configuration config = getBaseContext().getResources()
+ .getConfiguration();
+ currentLocale = config.locale.getLanguage();
+
+ bindService(new Intent(
+ "com.android.vending.billing.MarketBillingService.BIND"),
+ mServiceConn, Context.BIND_AUTO_CREATE);
+
+ initIAB(false);
+
+ FMOD.init(this);
+
+ try {
+ ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
+ Bundle bundle = ai.metaData;
+ isDistributionBuild = bundle.getBoolean("isDistributionBuild");
+ ChartboostHelper.onCreate(me, new ChartboostDelegate() {});
+ } catch (NameNotFoundException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ isDistributionBuild = true;
+ }
+
+ asyncOperationActive = false;
+
+ AndroidNDKHelper.SetNDKReciever(this);
+
+ uiHelper = new UiLifecycleHelper(this, null);
+ uiHelper.onCreate(savedInstanceState);
+
+ GoblinDefendersApplication.activityResumed();
+
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+
+ mDecorView = getWindow().getDecorView();
+ final GestureDetector clickDetector = new GestureDetector(this,
+ new GestureDetector.SimpleOnGestureListener() {
+ @Override
+ public boolean onSingleTapUp(MotionEvent e) {
+ hideSystemUI();
+ return true;
+ }
+ });
+
+ try {
+ PackageManager pm = getPackageManager();
+ Signature sig = pm.getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
+ md5Fingerprint = doFingerprint(sig.toByteArray(), "MD5").toUpperCase();
+ } catch (Exception e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+
+ if (!isFromGooglePlay())
+ {
+ this.showDialog(getString(R.string.error), getString(R.string.reinstall));
+ }
+
+ getAccountNames();
+ }
+
+ public Cocos2dxGLSurfaceView onCreateView() {
+ Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
+ Log.d("gd2-main", "onCreateView");
+ glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
+
+ return glSurfaceView;
+ }
+
+ @TargetApi(Build.VERSION_CODES.HONEYCOMB)
+ private void hideSystemUI() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
+ return;
+
+ mDecorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+ | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_LOW_PROFILE
+ | View.SYSTEM_UI_FLAG_IMMERSIVE);
+ }
+
+ @TargetApi(Build.VERSION_CODES.HONEYCOMB)
+ @Override
+ public void onWindowFocusChanged(boolean hasFocus) {
+ super.onWindowFocusChanged(hasFocus);
+
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
+ return;
+
+ if (hasFocus) {
+ mDecorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+ | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
+ }
+ }
+
+ private void initIAB(final boolean buyAfterLogin) {
+ // in-app billing
+ String base64EncodedPublicKey = SampleDownloaderService.BASE64_PUBLIC_KEY;
+ // compute your public key and store it in base64EncodedPublicKey
+ mHelper = new IabHelper(this, base64EncodedPublicKey);
+ mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
+ public void onIabSetupFinished(IabResult result) {
+ if (!result.isSuccess()) {
+ // Oh noes, there was a problem.
+ Log.d(this.toString(),
+ "Problem setting up In-app Billing: " + result);
+ }
+ Log.d(this.toString(), "Hooray, IAB is fully set up!");
+ if (buyAfterLogin)
+ buyGear(inAppID, inAppEvent, flyerMsg, inAppTag, inAppConsumable);
+ }
+ });
+ }
+
+ private void loadAlaStatWrapperConfigFromTestFile() {
+
+ // convert res/raw input stream to file
+ File propsFile = new File(getFilesDir(), "alawar.properties");
+
+ try {
+
+ Scanner scaner = new Scanner(this.getResources().openRawResource(
+ R.raw.alawar));
+ BufferedWriter writer = new BufferedWriter(
+ new FileWriter(propsFile));
+
+ while (scaner.hasNextLine()) {
+ writer.write(scaner.nextLine());
+ writer.newLine();
+ }
+
+ writer.close();
+ scaner.close();
+
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ // read AlaStatProperties from file
+
+ AlaStatWrapper.loadConfigFromPropertiesFile(propsFile);
+
+ }
+
+ public static void logEventAlawar(String eventName, String st1, String st2, String st3, int v, int l, String parameters) {
+
+ Log.d("LOGEVENT", eventName + " " + st1 + " " + st2 + " " + st3 + " " + v + " " + l + " " + parameters);
+
+ Map<String, String> data = new HashMap<String, String>();
+ data.put(AlaStatWrapper.KEY_ST1, st1);
+ data.put(AlaStatWrapper.KEY_ST2, st2);
+ data.put(AlaStatWrapper.KEY_ST3, st3);
+ data.put(AlaStatWrapper.KEY_V, Integer.toString(v));
+ data.put(AlaStatWrapper.KEY_L, Integer.toString(l));
+ data.put(AlaStatWrapper.KEY_DATA, parameters);
+
+ AlaStatWrapper.logEvent(eventName, data);
+ }
+
+ public static void showInterstitial(final String msg) {
+ Log.d("Chartboost", "Showing banner on " + msg);
+ /*
+ * Handler handler = new Handler(me.getMainLooper()); handler.post( new
+ * Runnable() {
+ *
+ * @Override public void run() {
+ *
+ * } } );
+ */
+ me.runOnUiThread(new Runnable() {
+
+ @Override
+ public void run() {
+ ChartboostHelper.showInterstitial(msg);
+ }
+ });
+ }
+
+ public static void flurryLevelEnd(String event, String key, String value) {
+ Map<String, String> mp = new HashMap<String, String>();
+ mp.put(key, value);
+ Log.d("flurry", event + " " + key + " " + value);
+ FlurryAgent.logEvent(event, mp);
+ }
+
+ private static String getHash(String str) throws NoSuchAlgorithmException,
+ UnsupportedEncodingException {
+
+ MessageDigest m = MessageDigest.getInstance("MD5");
+ m.reset();
+ m.update(str.getBytes("utf-8"));
+
+ String s2 = new BigInteger(1, m.digest()).toString(16);
+ StringBuilder sb = new StringBuilder(32);
+
+ for (int i = 0, count = 32 - s2.length(); i < count; i++) {
+ sb.append("0");
+ }
+
+ return sb.append(s2).toString();
+ }
+
+ private static boolean checkInternets() {
+ final ConnectivityManager connectManager = (ConnectivityManager) me
+ .getSystemService(Context.CONNECTIVITY_SERVICE);
+
+ final NetworkInfo mobile = connectManager
+ .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
+ final NetworkInfo wifi = connectManager
+ .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+
+ // Return true if connected, either in 3G or wi-fi
+ return ((mobile != null && mobile.getState() == NetworkInfo.State.CONNECTED) || (wifi != null && wifi
+ .getState() == NetworkInfo.State.CONNECTED));
+ }
+
+ public static void buyGear(final String productID, String flurryID, String flyer, int tag, boolean consumable) {
+ Log.d("InApp Billing", "Buy gear button clicked.");
+ // if (!checkInternets()) me.showDialog("Error",
+ // "No internet connection.");
+ FlurryAgent.logEvent("IAP_" + flurryID + "_Buy");
+ inAppTag = tag;
+ inAppEvent = flurryID;
+ inAppID = productID.toLowerCase();
+ inAppConsumable = consumable;
+
+ flyerMsg = flyer;
+
+ try {
+ Inventory inv = mHelper.queryInventory(true, null);
+ SkuDetails details = inv.getSkuDetails(inAppID);
+ if (details != null)
+ inAppCurrencyCode = details.getPriceCurrencyCode();
+ Log.d("in-app", "buy gear currency code: " + inAppCurrencyCode);
+ if (inv.hasPurchase(productID)) {
+ Log.d("IAB", "Hey, we gonna try to restore your purchase.");
+ final Purchase purchase = inv.getPurchase(productID);
+ if (purchase != null)
+ {
+ runOnBackgroundThread(new Runnable() {
+ @Override
+ public void run() {
+ if (!validReceipt(purchase)) {
+ completeTransactionOnGLThread(productID, 1);
+ }
+ else
+ completeTransactionOnGLThread(productID, 2);
+ }
+ });
+ }
+ else
+ {
+ Log.d("in-app", "purchase is null");
+ }
+
+ // completeTransactionOnGLThread(productID, 1);
+ } else {
+ mHelper.launchPurchaseFlow(me, productID, tag,
+ mPurchaseFinishedListener);
+ }
+ } catch (IabException e) {
+ completeTransactionOnGLThread(inAppID, 1);
+ e.printStackTrace();
+ } catch (NullPointerException e) {
+ completeTransactionOnGLThread(inAppID, 1);
+ e.printStackTrace();
+ } catch (IllegalStateException e) {
+ e.printStackTrace();
+ loginIntoGooglePlay();
+ }
+ }
+
+ private static void loginIntoGooglePlay() {
+ List<String> accounts = getAccountNames();
+
+ if (!accounts.isEmpty()) {
+ me.showDialog("In-App purchases are unavailable",
+ "Please update your version of Google Play.");
+ } else {
+ Intent intent = AccountPicker.newChooseAccountIntent(null, null,
+ new String[] { "com.google" }, false, null, null, null,
+ null);
+ me.startActivityForResult(intent, GOOGLE_LOGIN_ACTIVITY_RESULT);
+ }
+ }
+
+ private static List<String> getAccountNames() {
+ AccountManager mAccountManager = AccountManager.get(me);
+ Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
+ List<String> names = new ArrayList<String>();
+ for (int i = 0; i < accounts.length; i++) {
+ names.add(accounts[i].name);
+ if (testAccounts.indexOf(accounts[i].name) != -1)
+ testPurchase = true;
+ }
+ return names;
+ }
+
+ public static void restorePurchase(final String productID) {
+ Log.d("Restore", "restoring purchase " + productID);
+
+ try
+ {
+ Inventory inv = mHelper.queryInventory(true, null);
+ if (inv.hasPurchase(productID)) {
+ final Purchase purchase = inv.getPurchase(productID);
+ if (purchase != null) {
+ runOnBackgroundThread(new Runnable() {
+ @Override
+ public void run() {
+ if (!validReceipt(purchase)) {
+ completeTransactionOnGLThread(productID, 1);
+ } else
+ completeTransactionOnGLThread(productID, 2);
+ }
+ });
+ }
+ }
+ } catch (IabException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+
+ } catch (IllegalStateException e) {
+ e.printStackTrace();
+ } catch (NullPointerException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public static void restoreConsumablePurchases() {
+
+ if (asyncOperationActive)
+ return;
+
+ try
+ {
+ Inventory inv = mHelper.queryInventory(true, null);
+ final List<Purchase> purchases = new ArrayList<Purchase>();
+ for (int i = 0; i < consumableInApps.length; ++i) {
+ Purchase gemPurchase = inv.getPurchase(consumableInApps[i]);
+ if (gemPurchase != null) {
+ Log.d("IAB", "We have gems. Consuming it.");
+ purchases.add(gemPurchase);
+ }
+ }
+ if (purchases.size() > 0)
+ {
+ asyncOperationActive = true;
+ me.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mHelper.consumeAsync(purchases, mConsumeMultiFinishedListener);
+ }
+ });
+ }
+ } catch (IabException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (NullPointerException e) {
+ e.printStackTrace();
+ } catch (IllegalStateException e) {
+ e.printStackTrace();
+ }
+ }
+
+ // Callback for when a purchase is finished
+ static IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
+ public void onIabPurchaseFinished(IabResult result, final Purchase purchase) {
+ Log.d("InApp Billing", "Purchase finished: " + result
+ + ", purchase: " + purchase);
+
+ String id = "";
+ if (purchase == null || purchase.getSku() == null
+ || purchase.getSku().equals(""))
+ id = inAppID;
+ else
+ id = purchase.getSku();
+
+ if (result.isFailure()) {
+ // Oh noes!
+ Log.d("InApp Billing", "Oh noes! Purchase failed!");
+ FlurryAgent.logEvent("IAP_" + inAppEvent + "_Close");
+
+ completeTransactionOnGLThread(id, 1);
+
+ return;
+ }
+
+ Log.d("InApp Billing", "Purchase successful.");
+ FlurryAgent.logEvent("IAP_" + inAppEvent + "_Done");
+
+ AlaStatWrapper.revenueTracking(inAppCurrencyCode,
+ Math.round(100 * Float.parseFloat(flyerMsg)));
+
+ if (!inAppConsumable) {
+ Log.d("InApp Billing", "Purchase is non-consumable.");
+ final String iap = id;
+ runOnBackgroundThread(new Runnable() {
+
+ @Override
+ public void run() {
+ if (!validReceipt(purchase)) {
+ me.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ new AlertDialog.Builder(me)
+ .setTitle("Error")
+ .setMessage(
+ "Purchase validation failed!")
+ .setCancelable(false)
+ .setPositiveButton(
+ "OK",
+ new DialogInterface.OnClickListener() {
+ public void onClick(
+ DialogInterface dialog,
+ int which) {
+
+ }
+ }).show();
+ }
+ });
+ completeTransactionOnGLThread(iap, 1);
+ }
+ else
+ completeTransactionOnGLThread(iap, 0);
+ }
+ });
+
+ } else {
+ Log.d("InApp Billing",
+ "Purchase is consumable. Starting gear consumption.");
+ mHelper.consumeAsync(purchase, mConsumeFinishedListener);
+ }
+ }
+ };
+
+ public static boolean isNeedsUpdate()
+ {
+ try {
+ return true;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
+ }
+
+ public static void updateGame(String link)
+ {
+ Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
+ me.startActivity(browserIntent);
+ }
+
+ private static void runOnBackgroundThread(Runnable runnable) {
+
+ if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
+ BackgroundExecutor.execute(runnable);
+ } else {
+ runnable.run();
+ }
+ }
+
+ public static boolean validReceipt(Purchase purchase) {
+ try {
+ String productID = purchase.getSku();
+ boolean retVal = false;
+ int status = 1;
+ String urlsting;
+ if (isDistributionBuild)
+ urlsting = "http://gd.f2p.services.alawar.com/purchase/android/";
+ else
+ urlsting = "http://gd-copy.f2p.services.alawar.com/purchase/android/";
+
+ URL url = new URL(urlsting);
+ HttpRequestBase theRequest = new HttpPost(url.toURI());
+
+ JSONObject json = new JSONObject();
+ json.put("platform", "Android");
+ json.put("package", bundleID());
+ json.put("responseData", purchase.getOriginalJson());
+ json.put("signature", purchase.getSignature());
+
+ ((HttpPost) theRequest).setEntity(new StringEntity(json.toString()));
+
+ theRequest.addHeader("Accept", "application/json");
+ theRequest.addHeader(HTTP.CONTENT_TYPE, "application/json");
+
+ DefaultHttpClient httpClient = new DefaultHttpClient();
+ HttpResponse urlResponse = httpClient.execute(theRequest);
+
+ if (urlResponse == null || urlResponse.getStatusLine() == null
+ || urlResponse.getStatusLine().getStatusCode() >= 400) {
+ retVal = false;
+ } else {
+ InputStream stream = urlResponse.getEntity().getContent();
+ JSONObject dic = getResponse(stream);
+ status = dic.getInt("status");
+
+ switch (status) {
+ case 200:
+ case 201:
+ case 202: {
+ retVal = true;
+ if (!dic.has("receipt"))
+ break;
+ if (productID != null
+ && productID.length() > 0
+ && (Arrays.asList(consumableInApps).contains(
+ productID) || Arrays.asList(
+ nonConsumableInApps).contains(productID))) {
+ retVal = true;
+ }
+ }
+ break;
+
+ default:
+ retVal = false;
+ break;
+ }
+ }
+
+ return retVal;
+ } catch (Exception exc) {
+ Log.d("in-app", "validation failed");
+ exc.printStackTrace();
+ return false;
+ }
+ }
+
+ public static JSONObject getResponse(InputStream stream) throws IOException, JSONException
+ {
+ String line;
+ BufferedReader reader;
+ StringBuilder response;
+ JSONObject jsonObject = null;
+
+ reader = new BufferedReader(new InputStreamReader(stream));
+ response = new StringBuilder();
+
+ while ((line = reader.readLine()) != null)
+ {
+ response.append(line).append('\r');
+ }
+
+ reader.close();
+
+ jsonObject = new JSONObject(response.toString());
+
+ return jsonObject;
+ }
+
+ // Called when consumption is complete
+ static IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
+ public void onConsumeFinished(final Purchase purchase, IabResult result) {
+ Log.d("InApp Billing", "Consumption finished. Purchase: "
+ + purchase + ", result: " + result);
+ asyncOperationActive = false;
+ // We know this is the "gas" sku because it's the only one we
+ // consume,
+ // so we don't check which sku was consumed. If you have more than
+ // one
+ // sku, you probably should check...
+
+ String id = "";
+ if (purchase == null || purchase.getSku() == null
+ || purchase.getSku().equals(""))
+ id = inAppID;
+ else
+ id = purchase.getSku();
+
+ if (result.isSuccess()) {
+ // successfully consumed, so we apply the effects of the item in
+ // our
+ // game world's logic, which in our case means filling the gas
+ // tank a bit
+ final String iap = id;
+ runOnBackgroundThread(new Runnable() {
+
+ @Override
+ public void run() {
+ if (!validReceipt(purchase)) {
+ me.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ new AlertDialog.Builder(me)
+ .setTitle("Error")
+ .setMessage(
+ "Purchase validation failed!")
+ .setCancelable(false)
+ .setPositiveButton(
+ "OK",
+ new DialogInterface.OnClickListener() {
+ public void onClick(
+ DialogInterface dialog,
+ int which) {
+
+ }
+ }).show();
+ }
+ });
+ completeTransactionOnGLThread(iap, 1);
+ }
+ else
+ completeTransactionOnGLThread(iap, 0);
+ }
+ });
+
+ Log.d("InApp Billing", "Consumption successful. Provisioning.");
+ } else {
+ Log.d("InApp Billing", "Error while consuming: " + result);
+ completeTransactionOnGLThread(id, 1);
+ }
+
+ Log.d("InApp Billing", "End consumption flow.");
+ }
+ };
+
+ static IabHelper.OnConsumeMultiFinishedListener mConsumeMultiFinishedListener = new IabHelper.OnConsumeMultiFinishedListener() {
+
+ @Override
+ public void onConsumeMultiFinished(List<Purchase> purchases, List<IabResult> results) {
+ for (int i = 0; i < purchases.size(); ++i)
+ {
+ final Purchase purchase = purchases.get(i);
+ IabResult result = results.get(i);
+
+ if (purchase == null)
+ continue;
+
+ Log.d("InApp Billing", "Consumption finished. Purchase: "
+ + purchase + ", result: " + result);
+ // We know this is the "gas" sku because it's the only one we
+ // consume,
+ // so we don't check which sku was consumed. If you have more than
+ // one
+ // sku, you probably should check...
+
+ final String id = purchase.getSku();
+
+ if (result.isSuccess()) {
+ // successfully consumed, so we apply the effects of the item in
+ // our
+ // game world's logic, which in our case means filling the gas
+ // tank a bit
+
+ runOnBackgroundThread(new Runnable() {
+ @Override
+ public void run() {
+ if (!validReceipt(purchase)) {
+ completeTransactionOnGLThread(id, 1);
+ }
+ else
+ completeTransactionOnGLThread(id, 0);
+ }
+ });
+
+ Log.d("InApp Billing", "Consumption successful. Provisioning.");
+ } else {
+ Log.d("InApp Billing", "Error while consuming: " + result);
+ completeTransactionOnGLThread(id, 1);
+ }
+
+ Log.d("InApp Billing", "End consumption flow.");
+ }
+ asyncOperationActive = false;
+ }
+ };
+
+ public static void showOfferWall() {
-
++ SponsorPayHelper.showOfferwall(me);
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ Log.d("onActivityResult", "(" + requestCode + "," + resultCode + ","
+ + data);
+
+ // Pass on the activity result to the helper for handling
+ if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
+ if (requestCode == GOOGLE_LOGIN_ACTIVITY_RESULT)
+ switch (resultCode) {
+ case RESULT_OK:
+ {
+ getAccountNames();
+ initIAB(true);
+ }
+ break;
+ case RESULT_CANCELED:
+ completeTransactionOnGLThread(inAppID, 1);
+ break;
+ }
- /*
- SPCurrencyServerListener requestListener = new SPCurrencyServerListener() {
-
- @Override
- public void onSPCurrencyServerError(
- CurrencyServerAbstractResponse response) {
- Log.d("SPCurrencyServerListener",
- "Request or Response Error: "
- + response.getErrorType());
- }
+
- @Override
- public void onSPCurrencyDeltaReceived(
- CurrencyServerDeltaOfCoinsResponse response) {
- Log.d("SPCurrencyServerListener",
- "Response From Currency Server. Delta of Coins: "
- + String.valueOf(response.getDeltaOfCoins())
- + ", Latest Transaction Id: "
- + response.getLatestTransactionId());
- reward = (int) response.getDeltaOfCoins();
- addGearOfferwall(reward);
- }
- };
- SponsorPayPublisher.requestNewCoins(getApplicationContext(),
- requestListener);
- */
+ super.onActivityResult(requestCode, resultCode, data);
++
+ if (Session.getActiveSession() != null)
+ Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
+
+ uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
+ @Override
+ public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
+ Log.e("Activity", String.format("Error: %s", error.toString()));
+ AndroidNDKHelper.SendMessageWithParameters("onShareDialogClosed", null);
+ }
+
+ @Override
+ public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
+ Log.i("Activity", "Success!");
+
+ final String postId = FacebookDialog.getNativeDialogPostId(data);
+ if (postId != null) {
+ Log.d("FB", "Posted story, id: " + postId);
+ AndroidNDKHelper.SendMessageWithParameters("onStoryPublished", null);
+ } else {
+ // User clicked the Cancel button
+ Log.d("FB", "User canceled story publishing.");
+ AndroidNDKHelper.SendMessageWithParameters("onShareDialogClosed", null);
+ }
+ }
+ });
-
++
++ SponsorPayHelper.onActivityResult(this, requestCode, resultCode, data);
+ } else {
+ Log.d("onActivityResult", "handled by IABUtil.");
+ }
+ }
+
+ public static void gotGear() {
+ reward = 0;
+ }
+
+ public static void queryGear() {
- addGearOfferwall(reward);
++ me.runOnGLThread(new Runnable() {
++ @Override
++ public void run() {
++ addGearOfferwall(reward);
++ }
++ });
+ }
+
+ @Override
+ public void onLowMemory() {
+ super.onLowMemory();
+ Log.d("WARNING!", "Low memory!!!");
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ Log.d("gd2-main", "onStart");
+
+ String versionName = "1.0";
+
+ try {
+ versionName = this.getPackageManager().getPackageInfo(
+ this.getPackageName(), 0).versionName;
+ } catch (NameNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ Log.d("versionName", versionName);
-
++
++ SponsorPayHelper.start(this, "28782", "81909dd9638816fea0ceed3536f23751", hash, this);
++
+ AlaStatWrapper.setAppVersion(versionName);
+ AlaStatWrapper.setEventLoggingEnabled(true);
+ AlaStatWrapper.onStartSession(this);
+ //FlurryAgent.onStartSession(this, "M6WZ2VD75T6SX3HJDYSH");
+ //AlaStatWrapper.setUserId(hash);
+
+ // Notify the beginning of a user session. Must not be dependent on user
+ // actions or any prior network requests.
+ ChartboostHelper.onStart(this);
+ GoblinDefendersApplication.activityResumed();
+ openInbox();
+ }
+
+ @Override
+ protected void onStop() {
+ // autoSerialize();
+ Log.d("gd2-main", "onStop");
+ super.onStop();
+ ChartboostHelper.onStop(this);
+ GoblinDefendersApplication.activityPaused();
+ }
+
+ @Override
+ protected void onPause() {
+ // pauseGame();
+ // autoSerialize();
+ Log.d("gd2-main", "onPause");
+ GoblinDefendersApplication.activityPaused();
+ super.onPause();
+ // mGLView.onPause();
+ uiHelper.onPause();
+ // Logs 'app deactivate' App Event.
+ AppEventsLogger.deactivateApp(this);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ Log.d("gd2-main", "onResume");
+ uiHelper.onResume();
+ GoblinDefendersApplication.activityResumed();
+ // Logs 'install' and 'app activate' App Events.
+ AppEventsLogger.activateApp(this);
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ uiHelper.onSaveInstanceState(outState);
+ }
+
+ @Override
+ protected void onDestroy() {
+ // autoSerialize();
+ AlaStatWrapper.onEndSession(me);// FlurryAgent.onEndSession(this);
+ Log.d("gd2-main", "onDestroy");
+ FMOD.close();
+
+ if (mServiceConn != null)
+ unbindService(mServiceConn);
+ if (mHelper != null)
+ mHelper.dispose();
+
+ mHelper = null;
+ GoblinDefendersApplication.activityPaused();
+ super.onDestroy();
+ uiHelper.onDestroy();
+ ChartboostHelper.onDestroy(this);
+ }
+
+ @Override
+ public void onBackPressed() {
+
+ // If an interstitial is on screen, close it. Otherwise continue as
+ // normal.
+ if (ChartboostHelper.onBackPressed())
+ return;
+ else
+ super.onBackPressed();
+ }
+
+ public static String getDeviceID() {
+ return hash;
+ }
+
+ public static void showSubscribe() {
+ Intent intent = new Intent(me, SubscriberActivity.class);
+ intent.putExtra(SubscriberActivity.APPLICATION_NAME,
+ me.getString(R.string.app_name));
+ me.startActivity(intent);
+ }
+
+ public static void showAlertProfile(final String title, final String message,
+ final String cancelBtn, final String otherBtn) {
+ Log.d("alert", "shown");
+ me.runOnUiThread(new Runnable() {
+
+ @Override
+ public void run() {
+ new AlertDialog.Builder(me)
+ .setTitle(title)
+ .setMessage(message)
+ .setCancelable(false)
+ .setPositiveButton(otherBtn,
+ new DialogInterface.OnClickListener() {
+ public void onClick(
+ DialogInterface dialog,
+ int which) {
+ me.runOnGLThread(new Runnable() {
+ @Override
+ public void run() {
+ syncProgress();
+ }
+ });
+ }
+ })
+ .setOnCancelListener(new DialogInterface.OnCancelListener() {
+ @Override
+ public void onCancel(DialogInterface dialog) {
+ me.runOnGLThread(new Runnable() {
+ @Override
+ public void run() {
+ requestCleanProfile();
+ }
+ });
+ }
+ })
+ .setNegativeButton(cancelBtn,
+ new DialogInterface.OnClickListener() {
+ public void onClick(
+ DialogInterface dialog,
+ int which) {
+ me.runOnGLThread(new Runnable() {
+ @Override
+ public void run() {
+ requestCleanProfile();
+ }
+ });
+ }
+ }).show();
+ }
+ });
+ }
+
+ public static void showAlert(final int eventID,
+ final String title, final String msg, final String cancelBtn,
+ final String otherBtn) {
+
+ me.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ new AlertDialog.Builder(me)
+ .setTitle(title)
+ .setCancelable(false)
+ .setMessage(msg)
+ .setPositiveButton(otherBtn,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog,
+ int which) {
+ me.runOnGLThread(new Runnable() {
+ @Override
+ public void run() {
+ sendEvent(eventID);
+ }
+ });
+ }
+ })
+ .setNegativeButton(cancelBtn,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog,
+ int which) {
+
+ }
+ }).show();
+ }
+ });
+ }
+
+ @Override
+ public void onConfigurationChanged(Configuration newConfig) {
+ super.onConfigurationChanged(newConfig);
+ Log.d("config", "changed");
+ String newLocale = newConfig.locale.getLanguage();
+ if (!currentLocale.equals(newLocale)) {
+ localeChanged();
+ currentLocale = newLocale;
+ }
+ }
+
+ public static void showReview(final String title, final String btnYes,
+ final String btnLater, final String btnNo) {
+ FlurryAgent.logEvent("RateIT_Tap");
+
+ me.runOnUiThread(new Runnable() {
+
+ @Override
+ public void run() {
+ new AlertDialog.Builder(me)
+ .setTitle("GoblinDefenders")
+ .setCancelable(false)
+ .setMessage(title)
+ .setPositiveButton(btnYes,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog,
+ int which) {
+ FlurryAgent.logEvent("RateIT_Yes");
+ Intent browserIntent = new Intent(
+ Intent.ACTION_VIEW,
+ Uri.parse("market://details?id=com.alawar.GoblinDefenders1"));
+ me.startActivity(browserIntent);
+ reviewResult(1);
+ }
+ })
+ .setNegativeButton(btnNo,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog,
+ int which) {
+ FlurryAgent.logEvent("RateIT_No");
+ reviewResult(2);
+ }
+ })
+ .setNeutralButton(btnLater,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog,
+ int which) {
+ FlurryAgent.logEvent("RateIT_Later");
+ reviewResult(0);
+ }
+ }).show();
+ }
+ });
+
+ }
+
+ public static void openUrl(String url) {
+ if (url.startsWith("vk:"))
+ url = url.replace("vk:", "http:");
+
+ Log.d("url", url);
+
+ try {
+ Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
+ me.startActivity(browserIntent);
+ } catch (Exception exc) {
+ exc.printStackTrace();
+ }
+ }
+
+ public static String getDeviceName() {
+ String manufacturer = Build.MANUFACTURER;
+ String model = Build.MODEL;
+ if (model.startsWith(manufacturer)) {
+ return capitalize(model);
+ } else {
+ return capitalize(manufacturer) + " " + model;
+ }
+ }
+
+
+ private static String capitalize(String s) {
+ if (s == null || s.length() == 0) {
+ return "";
+ }
+ char first = s.charAt(0);
+ if (Character.isUpperCase(first)) {
+ return s;
+ } else {
+ return Character.toUpperCase(first) + s.substring(1);
+ }
+ }
+
+ public static void showExitAlert(final String title, final String msg, final String btnYes, final String btnNo) {
+ me.runOnUiThread(new Runnable() {
+
+ @Override
+ public void run() {
+ new AlertDialog.Builder(me)
+ .setTitle(title)
+ .setMessage(msg)
+ .setCancelable(false)
+ .setPositiveButton(btnYes,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog,
+ int which) {
+ exitGame();
+ }
+ })
+ .setNegativeButton(btnNo,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog,
+ int which) {
+
+ }
+ }).show();
+ }
+ });
+ }
+
+ public static void hideMainActivity(){
+ me.moveTaskToBack(true);
+ }
+
+ public static void showMail(String msg) {
+ Intent i = new Intent(Intent.ACTION_SEND);
+ i.setType("text/html");
+ i.putExtra(Intent.EXTRA_EMAIL, new String[] { supportEmail });
+
+ String versionName = "0";
+ int versionCode = 0;
+ String device = getDeviceName();
+ String androidVersion = android.os.Build.VERSION.RELEASE;
+
+ try {
+ PackageInfo info = me.getPackageManager().getPackageInfo(me.getPackageName(), 0);
+ versionName = info.versionName;
+ versionCode = info.versionCode;
+ } catch (NameNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ String title = "GD2 ver:" + versionName + "(" + versionCode + ") device:" + device + " firmware:" + androidVersion;
+ i.putExtra(Intent.EXTRA_SUBJECT, title);
+ i.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(msg));
+ try {
+ me.startActivity(Intent.createChooser(i, "Send mail..."));
+
+ } catch (android.content.ActivityNotFoundException ex) {
+ Toast.makeText(me, "There are no email clients installed.",
+ Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ public static void getInAppDetails() throws IabException {
+ try {
+ if (!checkInternets()) {
+ priceQueryOver(false);
+ return;
+ }
+
+ if (mInventory == null) {
+ ArrayList<String> skuList = new ArrayList<String>();
+ for (int i = 0; i < consumableInApps.length; ++i) {
+ skuList.add(consumableInApps[i]);
+ }
+ for (int i = 0; i < nonConsumableInApps.length; ++i) {
+ skuList.add(nonConsumableInApps[i]);
+ }
+ mInventory = mHelper.queryInventory(true, skuList);
+ }
+
+ for (int i = 0; i < consumableInApps.length; ++i) {
+ SkuDetails details = mInventory
+ .getSkuDetails(consumableInApps[i]);
+ if (details != null)
+ {
+ setInAppPrice(details.getSku(), details.getPrice());
+ inAppCurrencyCode = details.getPriceCurrencyCode();
+ Log.d("in-app", "currency code: " + inAppCurrencyCode);
+ }
+ }
+
+ for (int i = 0; i < nonConsumableInApps.length; ++i) {
+ SkuDetails details = mInventory
+ .getSkuDetails(nonConsumableInApps[i]);
+ setInAppPrice(details.getSku(), details.getPrice());
+ }
+
+ priceQueryOver(true);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static boolean isDistributionBuild()
+ {
+ return isDistributionBuild;
+ }
+
+ public static boolean isDistributionBuildValue()
+ {
+ return isDistributionBuild && !testPurchase;
+ }
+
+ public static String buildNumber()
+ {
+ try {
+ PackageInfo info = me.getPackageManager().getPackageInfo(me.getPackageName(), 0);
+ return info.versionName;
+
+ } catch (NameNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ return "";
+ }
+ }
+
+ public static String SocialNetwork()
+ {
+ try {
+ ApplicationInfo ai = me.getPackageManager().getApplicationInfo(me.getPackageName(), PackageManager.GET_META_DATA);
+ Bundle bundle = ai.metaData;
+ return bundle.getString("SocialNetwork");
+
+ } catch (NameNotFoundException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ return "";
+ }
+ }
+
+ public static String bundleID()
+ {
+ ApplicationInfo applicationInfo = me.getApplicationInfo();
+ return applicationInfo.packageName;
+ }
+
+ public static void sendNotification(int addTime, String str, String notificationId) {
+ Calendar cal = Calendar.getInstance();
+ // add 5 minutes to the calendar object
+ cal.add(Calendar.SECOND, addTime);
+ Intent intent = new Intent(me, AlarmReceiver.class);
+ intent.putExtra("str", str);
+ if (notificationId != null)
+ intent.putExtra("id", notificationId);
+ else
+ intent.putExtra("id", "0");
+
+ int id = Integer.parseInt(notificationId);
+ PendingIntent sender = PendingIntent.getBroadcast(me, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
+
+ // Get the AlarmManager service
+ AlarmManager am = (AlarmManager) me.getSystemService(ALARM_SERVICE);
+ am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
+
+ Integer time = notifications.get(id);
+ if (time == null)
+ notifications.put(id, cal.get(Calendar.SECOND));
+ else if (GoblinDefenders.timeToNotificationWithId(notificationId) <= 0) {
+ notifications.remove(id);
+ notifications.put(id, cal.get(Calendar.SECOND));
+ }
+ }
+
+ public static void removeNotificationWithId(String notificationId)
+ {
+ int id = Integer.parseInt(notificationId);
+ PendingIntent intent = PendingIntent.getBroadcast(me, id, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
+
+ if (intent != null)
+ {
+ AlarmManager alarmManager = (AlarmManager) me.getSystemService(ALARM_SERVICE);
+ alarmManager.cancel(intent);
+ intent.cancel();
+ notifications.remove(id);
+ }
+ }
+
+ public static int timeToNotificationWithId(String notificationId)
+ {
+ int currentTime = Calendar.getInstance().get(Calendar.SECOND);
+ Integer notifyTime = notifications.get(Integer.parseInt(notificationId));
+ if (notifyTime == null)
+ return -1;
+
+ int timeLeft = notifyTime - currentTime;
+ return timeLeft;
+ }
+
+ public static void setUserID(String id)
+ {
+ Crashlytics.setUserIdentifier(id);
+ }
+
+ public static void setCheckpoint(String value)
+ {
+ Crashlytics.setString("CheckPoint", value);
+ }
+
+ public static String getFigerprint()
+ {
+ return md5Fingerprint;
+ }
+
+ private boolean isFromGooglePlay() {
+ PackageManager packageManager = this.getPackageManager();
+ String installPM = packageManager.getInstallerPackageName(getApplicationInfo().packageName);
+ if ( installPM == null ) {
+ // Definitely not from Google Play
+ return false;
+ } else if ( installPM.equals("com.google.android.feedback") ) {
+ // Installed from the Google Play
+ return true;
+ } else if ( installPM.equals("com.android.vending") ) {
+ return true;
+ }
+ return false;
+ }
+
+ protected static String doFingerprint(byte[] certificateBytes, String algorithm)
+ throws Exception {
+ MessageDigest md = MessageDigest.getInstance(algorithm);
+ md.update(certificateBytes);
+ byte[] digest = md.digest();
+
+ String toRet = "";
+ for (int i = 0; i < digest.length; i++) {
+ if (i != 0)
+ toRet += ":";
+ int b = digest[i] & 0xff;
+ String hex = Integer.toHexString(b);
+ if (hex.length() == 1)
+ toRet += "0";
+ toRet += hex;
+ }
+ return toRet;
+ }
+
+ static {
+ System.loadLibrary("fmod");
+ System.loadLibrary("fmodstudio");
+ System.loadLibrary("game");
+ }
+
++ @Override
++ public void onRewardReceived(double amount, String transactionId) {
++ // TODO Auto-generated method stub
++ Log.d("SPCurrencyServerListener",
++ "Response From Currency Server. Delta of Coins: "
++ + amount
++ + ", Latest Transaction Id: "
++ + transactionId);
++ reward = (int)amount;
++ me.runOnGLThread(new Runnable() {
++ @Override
++ public void run() {
++ addGearOfferwall(reward);
++ }
++ });
++ }
++
++ @Override
++ public void onErrorOccured(String errorMessage) {
++ Log.d("SPCurrencyServerListener",
++ "Request or Response Error: "
++ + errorMessage);
++ }
++
+}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment