com.xdyou.sanguo.GameSanGuo.java Source code

Java tutorial

Introduction

Here is the source code for com.xdyou.sanguo.GameSanGuo.java

Source

/****************************************************************************
Copyright (c) 2010-2011 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.xdyou.sanguo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.WindowManager;

import com.appsflyer.AppsFlyerLib;
import com.chartboost.sdk.Chartboost;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Request.Callback;
import com.facebook.Request.GraphUserCallback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphPlace;
import com.facebook.model.GraphUser;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.gameanalytics.android.GameAnalytics;
import com.gmobi.trade.ICallback;
import com.gmobi.trade.TradeService;
import com.gocpa.android.sdk.GocpaTracker;
import com.gocpa.android.sdk.GocpaUtil;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.mobileapptracker.MobileAppTracker;
import com.mobvista.Tracker;
import com.sponsorpay.SponsorPay;
import com.tendcloud.tenddata.TalkingDataGA;

public class GameSanGuo extends Cocos2dxActivity {

    // hasoffers 
    public MobileAppTracker mobileAppTracker = null;

    // facebook ????APPIDvaluesstring.xmlappid?
    //   private final String APP_ID = "566941626743891";
    private final String APP_ID = "1543699082536762";

    private final String APP_LOGO_LINK = "http://privacypolicy.tw.xdyou.com/image/logo.png";
    private static Handler handler = null;

    //gocpa sdk appid
    private static final String GOCPA_APPID = "9d2d5abb56f74e6c984aa48c9626e34e";
    private static final String GOCPA_ADVID = "442";

    //GA SDK key&id
    private static final String GA_GAME_KEY = "8565cc41fc3d519b16be1254acf0ee04";
    private static final String GA_SCR_KEY = "7100775487b5ad597d11b376f5e8a76ea2bce9ff";

    // handler??
    // facebook?
    private static final int FB_LOGIN = 1;
    private static final int FB_LOGOUT = 2;
    private static final int FB_SHARE = 3;
    private static final int FB_CREATE_SESSION = 4;
    // url
    private static final int HANDLER_OPEN_URL = 10;
    // ?
    private static final int BUID_DIALOG = 7;

    private static final int GOTO_GOOGLE_PLAY = 5;

    //AppFlyers ?
    private static final int APP_FLYERS_LOGIN = 6;

    //MM: ?showMessage
    private static final int MSG_SHOW_TOAST = 20;

    //MM: ?setUserDataNative
    private static final int MSG_SET_USER_DATA = 21;

    private static boolean IS_PRE_LOGIN_FACEBOOK = false;

    //?FBtrueFBsessionFB?false
    private static boolean IS_LOGIN_FB_VIA_SHARING_CONTENT = false;

    // ???????
    private String imageName = "";
    private String message = "";
    //facebook ?
    String imageUrl = "";
    //facebook??id
    String imageId = "";

    // ?????loginKey
    private static String loginKey = "";

    private final static String MARKET_LINK = "market://details?id=";

    // ??facebook??
    private static final String PERMISSION = "publish_actions";
    // ??
    private static final String SHARE_FAILED_INFO = "! ?!";
    private static final String SHARE_SUCCESS_INFO = "?!";

    // facebookSession??
    private Session.StatusCallback statusCallback = new Session.StatusCallback() {
        @Override
        public void call(final Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };

    private int tempTick = 0;

    // facebook session ??????
    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        session = Session.getActiveSession();
        Log.e("FB", "onSessionStateChange call=" + tempTick + " begin!");

        // session??
        if (session != null && session.isOpened()) {
            Log.e("FB", "onSessionStateChange || session state changed!" + session.toString());

            // publish_actions???? ?
            if (session.getState().equals(SessionState.OPENED_TOKEN_UPDATED)) {
                postImageAndMessage();
                return;
            }

            // ?? public_profile
            loginKey = session.getAccessToken();
            Request.newMeRequest(session, new GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                    Log.e("FB", "onSessionStateChange onCompleted callback!");

                    String fbUserName = "";
                    String fbUserId = "";
                    if (user != null) {
                        // ?loginkey
                        Log.e("FB", "facebook token: " + loginKey);
                        Log.e("FB", "facebook id : " + user.getId());
                        Log.e("FB", "facebook username : " + user.getName());

                        fbUserName = user.getName();
                        fbUserId = user.getId();

                        // ???
                        if (IS_PRE_LOGIN_FACEBOOK == true) {
                            Log.e("FB", "onSessionStateChange || POST IMAGE=" + imageName);
                            IS_PRE_LOGIN_FACEBOOK = false;
                            IS_LOGIN_FB_VIA_SHARING_CONTENT = true;

                            // ?????
                            if (!hasPublishPermission()) {
                                Log.d("sanguo", "go2play fbShareContent || request permission");
                                requestNewPublishPermission();
                                return;
                            } else {
                                // ????
                                Log.d("sanguo", "go2play fbShareContent || publish content");
                                postImageAndMessage();
                            }
                        } else {
                            Log.e("FB", "onSessionStateChange || LOGIN DONE=" + imageName);
                            runFbUserIdAndUserName(fbUserName, fbUserId, loginKey, true);
                        }

                    }
                    if (response.getError() != null) {
                        // ??
                        Log.e("FB", "error : " + response.getError());
                    }
                }
            }).executeAsync();
        }

        Log.e("FB", "onSessionStateChange call=" + tempTick + " end!");
        tempTick++;
    }

    // C++
    // ?id??facebook
    public static native boolean fbUserIdAndUserName(String userName, String userId, String loginKey,
            boolean setFBState);

    // session?
    public static native void setSessionState(boolean state);

    // facebook????
    public static native void fbShareTips(String tips);

    // facebook
    public static native void fbDoLogout();

    // ???????????
    public static native void sendPostSuccess();

    // ??URL
    public static native String getClientUpdateUrl();

    // jnijavac++??cocos2d-x
    // thread??cocos2dxActivity???run
    public static void runFbUserIdAndUserName(final String userName, final String userId, final String loginKey,
            final boolean setFbState) {
        Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() {
            @Override
            public void run() {
                fbUserIdAndUserName(userName, userId, loginKey, setFbState);
            }
        });
    }

    public static void runSetSessionState(final boolean state) {
        Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() {
            @Override
            public void run() {
                runSetSessionState(state);
            }
        });
    }

    public static void runFbShareTips(final String tips) {
        Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() {
            @Override
            public void run() {
                fbShareTips(tips);
            }
        });
    }

    public static void runfbDoLogout() {
        Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() {
            @Override
            public void run() {
                fbDoLogout();
            }
        });
    }

    public static void runSendPostSuccess() {
        Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() {
            @Override
            public void run() {
                sendPostSuccess();
            }
        });
    }

    //getTalkingDataAppId?
    // for talkingdata AADCA30D169116CF80FCAEA8EB601177
    //private static final String talkingDataAppId = "191F6CA0284EFD11DCF6E8AAB81851D7";

    private static final String talkingDataAppId = getTalkingDataAppId();
    private static final String talkingDataChannelId = getTalkingDataAppChannel();

    //c++? talkingdata AppId
    public static native String getTalkingDataAppId();

    //c++? td AppChannelTag
    public static native String getTalkingDataAppChannel();

    private Chartboost cb; // for chartboost ad sdk
    private static Cocos2dxActivity mActivity = null;

    protected void onCreate(Bundle savedInstanceState) {
        Log.d("SGAPP", "onCreate");
        mActivity = this;
        super.onCreate(savedInstanceState);

        //AppsFlyerSDK initial 2015.1.12
        AppsFlyerLib.setAppsFlyerKey("6HRzTLQfzQHGBQ87KzZttH");
        //? AppsFlyer
        AppsFlyerLib.sendTracking(getApplicationContext());

        //GA sdk ?
        GameAnalytics.initialise(this, GA_SCR_KEY, GA_GAME_KEY);
        GameAnalytics.startSession(this);

        //MM: AdvertiserSDK 2014.11.26
        Tracker.conversionTrack(this, "zywx_sgyxlm_hk_mo_tw");

        //??
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // ========================?TalkingData 
        Log.d("SGAPP", "talkingdataAppid || " + talkingDataAppId);
        TalkingDataGA.init(this, talkingDataAppId, talkingDataChannelId);
        // ========================?TalkingData 

        // ===================Facebook ?
        // ??session
        this.createFBSession();
        // Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
        // ===================Facebook ?

        //GoCPA
        GocpaUtil.setAppId(GOCPA_APPID);
        GocpaUtil.setAdvertiserId(GOCPA_ADVID);
        GocpaUtil.setReferral(false);

        GocpaTracker.getInstance(this).reportDevice();

        // ==================Go2Play listener_Begin_=======================================
        TradeService.setOnBalanceChangedListener(new ICallback() {
            @Override
            public void onResult(boolean isSuccess, Bundle bundle, Throwable ths) {
                // ???
                if (isSuccess) {
                    Log.e("go2play", "Charged Success!");
                    Log.e("go2play", "Balance: " + TradeService.getBalance(false));
                }
            }

        });
        // ==================Go2Play listener_End_=========================================

        // ==================ChartBoost SDK _Begin_============================================

        // ?chartboost
        this.cb = Chartboost.sharedChartboost();

        // chartboostappIdappKey, sdk????
        final String appIdCB = "54af952a43150f627b0fbb4a";
        final String appSignatureCB = "bea16683ef974c0393cf55c41719ef694ae8a0d5";

        this.cb.onCreate(this, appIdCB, appSignatureCB, null);

        // ==================ChartBoost SDK_End_==============================================

        // ==================hasoffers _Begin_============================================
        MobileAppTracker.init(getApplicationContext(), "24078", "3fba6dcf91bc7251866e59278574f16a");
        mobileAppTracker = MobileAppTracker.getInstance();

        // Collect Google Play Advertising ID
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());

                    mobileAppTracker.setGoogleAdvertisingId(adInfo.getId(), adInfo.isLimitAdTrackingEnabled());
                } catch (IOException e) {

                } catch (GooglePlayServicesNotAvailableException e) {
                    mobileAppTracker.setAndroidId(Secure.getString(getContentResolver(), Secure.ANDROID_ID));
                } catch (GooglePlayServicesRepairableException e) {
                    // Encountered a recoverable error connecting to Google Play
                    // services.
                }
            }
        }).start();

        // For collecting Android ID, device ID, and MAC address
        // Before August 1st 2014, remove these calls - only Google AID should
        // be collected.
        mobileAppTracker.setAndroidId(Secure.getString(getContentResolver(), Secure.ANDROID_ID));
        String deviceId = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        mobileAppTracker.setDeviceId(deviceId);
        try {
            WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            mobileAppTracker.setMacAddress(wm.getConnectionInfo().getMacAddress());
        } catch (NullPointerException e) {
            System.out.println("NullPointerExp");
        }

        // ==================hasoffers  _End_===========================

        // ?? ?Handler????????facebook?
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case FB_LOGIN:
                    fbLogin();
                    break;
                case FB_LOGOUT:
                    fbLogout();
                    break;
                case FB_SHARE: {
                    // ?????????
                    String imageName = msg.obj.toString();
                    fbShareContent(imageName);
                }
                    break;
                case FB_CREATE_SESSION: {
                    createFBSession();
                }
                    break;
                case GOTO_GOOGLE_PLAY: {
                    enterGooglePlay();
                }
                    break;
                case BUID_DIALOG: {
                    buildDialog();
                }
                    break;
                case HANDLER_OPEN_URL: {
                    execOpenUrl((String) msg.obj);
                }
                    break;
                case APP_FLYERS_LOGIN: {
                    appFlyersTrackerLogin((String) msg.obj);
                }
                    break;
                case MSG_SHOW_TOAST: {
                    handleShowToast((String) msg.obj);
                }
                    break;
                case MSG_SET_USER_DATA: {
                    handleSetUserData((SgUserData) msg.obj);
                }
                    break;
                default:
                    Log.e("facebook", "error come out!");
                    System.out.println("oh shit!");
                    break;
                }
            }
        };

    }

    public Cocos2dxGLSurfaceView onCreateView() {
        Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
        // TestCpp should create stencil buffer
        glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);

        return glSurfaceView;
    }

    // c++facebooksession
    public static void callFBCreateSession() {
        Message createSession = new Message();
        createSession.what = FB_CREATE_SESSION;
        handler.sendMessage(createSession);

    }

    // c++ facebook 
    public static void callFBLogin() {
        Message loginMessage = new Message();
        loginMessage.what = FB_LOGIN;
        handler.sendMessage(loginMessage);
    }

    // c++  facebook 
    public static void callFBLogout() {
        Message logoutMessage = new Message();
        logoutMessage.what = FB_LOGOUT;
        handler.sendMessage(logoutMessage);
    }

    // c++ facebook 
    public static void callFBShare(String imageName, String message) {
        Message shareMessage = new Message();
        shareMessage.what = FB_SHARE;
        // ?
        shareMessage.obj = imageName;
        handler.sendMessage(shareMessage);
    }

    //c++  google play
    public static void callGotoGoolePlay() {
        Message gotoGP = new Message();
        gotoGP.what = GOTO_GOOGLE_PLAY;
        handler.sendMessage(gotoGP);
    }

    //appsflyer appc++
    public static void appsFlyerLoginTracker(String userId) {
        Message appFlyer = new Message();
        appFlyer.what = APP_FLYERS_LOGIN;
        appFlyer.obj = userId;
        handler.sendMessage(appFlyer);
    }

    public void appFlyersTrackerLogin(String userId) {
        // userId?
        AppsFlyerLib.sendTrackingWithEvent(getApplicationContext(), "Login", userId);
    }

    //gp/3rdurl 
    public void enterGooglePlay() {
        String url = this.getClientUpdateUrl();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Log.d("url", url);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    //c++  url
    public static void callOpenUrl(String url) {
        Message ou = new Message();
        ou.what = HANDLER_OPEN_URL;
        ou.obj = url;
        handler.sendMessage(ou);
    }

    //url
    public void execOpenUrl(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Log.d("sanguo", "openUrl" + url);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    // facebook login
    public void fbLogin() {
        Log.e("go2play", "facebook login!");
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            Log.e("go2play", "set permission");
            Session.OpenRequest op = new Session.OpenRequest(this);
            op.setCallback(statusCallback);
            session.openForRead(op);
        } else {
            Session.openActiveSession(this, true, statusCallback);
        }

    }

    // facebook logout
    public void fbLogout() {
        Log.e("go2play", "facebook logout!");
        Session session = Session.getActiveSession();
        if (!session.isClosed()) {
            runfbDoLogout();
            session.closeAndClearTokenInformation();
        }
    }

    // session?, session
    public void createSession() {
        Session activeSession = Session.getActiveSession();
        if (activeSession == null || activeSession.getState().isClosed()) {
            activeSession = new Session.Builder(this).setApplicationId(APP_ID).build();
            Session.setActiveSession(activeSession);
        }
    }

    // facebooksession
    public void createFBSession() {

        Log.e("go2play", "enter createFBCreate function!");
        Session session = Session.getActiveSession();
        if (session == null) {
            Log.e("go2play", "session is null");
            if (session == null) {
                session = new Session(this);
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }
        }
        // session??
        if (session != null && !session.isOpened()) {
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }
        }
    }

    // ??
    private void requestNewPublishPermission() {
        Session session = Session.getActiveSession();
        System.out.println("session in requestNewPublishPermission " + session.toString());

        // ?facebook publish_actions??
        if (session.isOpened()) {
            session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
            return;
        }
    }

    //facebook
    private void uploadImage(Bitmap mUploadBitmap) {
        // 
        if (mUploadBitmap != null && !mUploadBitmap.isRecycled()) {
            // // , ?
            Log.d("FB", "upload image");
            Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), mUploadBitmap,
                    mUploadCallback);
            request.executeAsync();
        }
    }

    private Callback mUploadCallback = new Callback() {
        @Override
        public void onCompleted(Response response) {
            Log.d("FB", "upload image completed");
            if (response.getError() != null) {
                Log.d("FB", "upload image error " + response.getError().toString());
            } else {
                // ?,?response  json
                JSONObject jsonObject = response.getGraphObject().getInnerJSONObject();
                try {
                    Log.d("FB", "get Json Data Success");
                    // get image id
                    imageId = jsonObject.getString("id");

                    Log.d("FB", imageId);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            doImageUrlRequest(imageId);
                        }
                    }).start();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } // end of onCompleted
    };

    String streamToJson(InputStream is) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }

    private String doImageUrlRequest(String imageID) {
        Log.d("FB", "start get image url");
        String FACEBOOK_URL = "https://graph.facebook.com/?";
        // http???
        HttpGet httpget = new HttpGet(
                FACEBOOK_URL + "id=" + imageID + "&access_token=" + Session.getActiveSession().getAccessToken());

        Log.d("FB",
                FACEBOOK_URL + "id=" + imageID + "&access_token=" + Session.getActiveSession().getAccessToken());

        HttpParams httpparams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpparams, 15000);
        HttpConnectionParams.setSoTimeout(httpparams, 30000);

        // http client
        HttpClient httpclient = new DefaultHttpClient(httpparams);
        try {
            HttpResponse response = httpclient.execute(httpget);

            if (response.getStatusLine().getStatusCode() == 200) {
                Log.d("FB", "http requst status 200");
                // ?json data
                String json = streamToJson(response.getEntity().getContent());
                Log.d("FB", json);

                // get the image url
                if (json.contains("picture")) {

                    Log.e("FB", json);
                    imageUrl = getImageUrl(json);
                    Log.d("FB", "image Url ===> " + imageUrl);
                    sendBuildMessage();

                } else {
                    Log.e("FB", "### ?facebookurl");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return imageUrl;
    }

    public void sendBuildMessage() {
        Message build = new Message();
        build.what = BUID_DIALOG;
        handler.sendMessage(build);
    }

    private void buildDialog() {
        //

        Bundle params = new Bundle();

        params.putString("app_id", APP_ID);
        params.putString("name", "?");
        params.putString("caption", "???");
        params.putString("description",
                "????");
        String url = this.getClientUpdateUrl();
        Log.d("buildDialog", "updateUrl=" + url);
        params.putString("link", url);
        params.putString("picture", APP_LOGO_LINK);

        WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(getActivity(), Session.getActiveSession(), params))
                .setOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(Bundle values, FacebookException error) {
                        Log.d("FB", "WebDialog build ");
                        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) {
                                runSendPostSuccess();
                            } else {
                                // User clicked the Cancel button
                                runFbShareTips(SHARE_FAILED_INFO);
                            }
                        } else if (error instanceof FacebookOperationCanceledException) {
                            // User clicked the "x" button
                            runFbShareTips(SHARE_FAILED_INFO);
                        } else {
                            // Generic, ex: network error
                            runFbShareTips(SHARE_FAILED_INFO);
                        }
                    }

                }).build();
        feedDialog.show();
    }

    private String getImageUrl(String json) throws JSONException {
        JSONObject jsonObj = new JSONObject(json);

        if (jsonObj.has("picture")) {
            Log.d("FB", "image Url [getImageUrl Json]" + jsonObj.getString("picture"));
            return jsonObj.getString("picture");
        } else {
            return null;
        }
    }

    // ???
    private void postImageAndMessage() {
        Bitmap image = null;
        if (imageName != null) {
            image = BitmapFactory.decodeFile(imageName);
            System.out.println("go2play -- image " + image);
        }
        //uploadImage(image);
        sendBuildMessage();

        //      Request request = newFaceBookRequest(Session.getActiveSession(),
        //            imageName, message, null, new Callback()
        //            {
        //               @Override
        //               public void onCompleted(Response response)
        //               {
        //                  // need publish_actions permission
        //                  if (response.getError() != null)
        //                  {
        //                     Log.d("sanguo", "go2play fbShareContent || failed! error=" + response.getError().getErrorMessage());
        //                     runFbShareTips(SHARE_FAILED_INFO);
        //                  }
        //                  else
        //                  {
        //                     Log.d("sanguo", "go2play fbShareContent || succeeded!");
        //                     // ???
        //                     // runFbShareTips(SHARE_SUCCESS_INFO);
        //                     // ???????
        //                     runSendPostSuccess();
        //                  }
        //               }
        //            });
        //      RequestAsyncTask task = new RequestAsyncTask(request);
        //      task.execute();
    }

    private Context getActivity() {
        return this.getContext();
    }

    // ?pulish_actions??
    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions");
    }

    // newFaceBookRequest
    public void fbShareContent(String imageName) {
        this.imageName = imageName;
        Session session = Session.getActiveSession();

        Log.e("FB", session.toString() + "state ||" + session.isOpened());
        if (!session.isOpened() && !session.isClosed()) {
            Log.d("FB", "create session");

            Session.OpenRequest op = new Session.OpenRequest(this);
            op.setCallback(statusCallback);
            session.openForRead(op);
            IS_PRE_LOGIN_FACEBOOK = true;
            return;
        }

        Log.d("sanguo", "go2play fbShareContent || imageName:" + imageName + "message:" + message + ",tk:"
                + session.getAccessToken());

        // ?????
        if (!hasPublishPermission()) {
            Log.d("sanguo", "go2play fbShareContent || request permission");
            requestNewPublishPermission();
            return;
        } else {
            // ????
            Log.d("sanguo", "go2play fbShareContent || publish content");
            postImageAndMessage();
        }

    }

    // ??
    public Request newFaceBookRequest(Session session, String imageName, String message, GraphPlace graphPlace,
            Callback callback) {
        // ?
        if (session != null && session.isOpened()) {
            System.out.println(
                    "go2play -- session = " + session.toString() + "session.isOpened : " + session.isOpened());
            Bitmap image = null;
            if (imageName != null) {
                image = BitmapFactory.decodeFile(imageName);
                System.out.println("go2play -- image " + image);
            }

            Bundle parameters = new Bundle();
            // ??
            if (graphPlace != null) {
                parameters.putString("place", graphPlace.getId());
            }
            // ?
            if (message != null) {
                parameters.putString("message", message);
            }
            // ?
            if (image != null) {
                parameters.putParcelable("picture", image);
                // ?
                return new Request(session, "me/photos", parameters, HttpMethod.POST, callback);
            }
            // ???
            return new Request(session, "me/feed", parameters, HttpMethod.POST, callback);
        } else {
            System.out.println("session is null or session is closed!");
            return null;
        }
    }

    public static String urlEncode(String str) {
        return str;
        //      try {
        //         return URLEncoder.encode(str, "UTF-8");
        //      } catch (UnsupportedEncodingException e) {
        //         e.printStackTrace();
        //         return "UFO_MAC_ADDRESS";
        //      }
    }

    // ?android mac?
    public static String getMacID() {
        String str = "mac_address";

        WifiManager wifi = (WifiManager) mActivity.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        str = info.getMacAddress();

        // ??imei?
        if (str == null) {
            TelephonyManager tm = (TelephonyManager) mActivity.getSystemService(TELEPHONY_SERVICE);
            str = tm.getDeviceId();
        }
        Log.e("mac_address", str);
        return str;
    }

    // ??
    public static void beforeAllocationGc() {
        System.gc();
    }

    // ? =====BEGIN======
    /*
    @Override
    public boolean dispatchKeyEvent(KeyEvent event)
    {
       if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
        && event.getAction() == KeyEvent.ACTION_DOWN
        && event.getRepeatCount() == 0)
       {
     AlertDialog.Builder build = new AlertDialog.Builder(this);
     build.setTitle("")
           .setMessage("??")
           .setPositiveButton("",
                 new DialogInterface.OnClickListener()
                 {
                    @Override
                    public void onClick(DialogInterface dialog,
                          int which)
                    {
                       finish();
                    }
                 })
           .setNegativeButton("?",
                 new DialogInterface.OnClickListener()
                 {
        
                    @Override
                    public void onClick(DialogInterface dialog,
                          int which)
                    {
                    }
                 }).show();
       }
       return super.dispatchKeyEvent(event);
    }
    */
    // ? =====END======

    // for chartboost and facebook sdk override
    @Override
    protected void onStart() {
        Log.d("SGAPP", "onStart");
        super.onStart();
        this.cb.onStart(this);
        // facebook
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    protected void onStop() {
        Log.d("SGAPP", "onStop");
        super.onStop();
        this.cb.onStop(this);
        // facebook
        Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    protected void onDestroy() {
        Log.d("SGAPP", "onDestroy");
        //clear fb session
        if (IS_LOGIN_FB_VIA_SHARING_CONTENT) {
            Log.e("FB", "IS_LOGIN_FB_VIA_SHARING_CONTENT! so we clear facebook session!");
            Session session = Session.getActiveSession();
            if (session != null) {
                session.closeAndClearTokenInformation();
            }
        }
        this.cb.onDestroy(this);
        // setSessionState(false);
        super.onDestroy();
        System.exit(0);
    }

    @Override
    public void onBackPressed() {
        if (this.cb.onBackPressed())
            return;
        else
            super.onBackPressed();
    }

    // facebook sdk override
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("sgresult", "req=" + requestCode + "result," + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // facebooksession?
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

    @Override
    protected void onResume() {
        Log.d("SGAPP", "onResume");
        super.onResume();
        //MM: FB
        com.facebook.AppEventsLogger.activateApp(this, APP_ID);

        //start sponsor
        try {
            SponsorPay.start("637a0987b77b1277eaa099e92f31787e", null, null, this);
        } catch (RuntimeException e) {
            Log.d("SGAPP", e.getLocalizedMessage());
        }

        TalkingDataGA.onResume(this);
        //MM: AdvertiserSDK 2014.11.26
        Tracker.conversionTrack(this, "zywx_sgyxlm_hk_mo_tw");

        //GA
        GameAnalytics.startSession(this);

        // hasoffers
        mobileAppTracker.setReferralSources(this);
        mobileAppTracker.measureSession();
    }

    @Override
    protected void onPause() {
        Log.d("SGAPP", "onPause");
        super.onPause();
        TalkingDataGA.onPause(this);
        GameAnalytics.stopSession();
    }

    //sdkcaller
    public static void tryShowToast(String notice) {
        Message msg = new Message();
        msg.what = MSG_SHOW_TOAST;
        msg.obj = notice;
        handler.sendMessage(msg);
    }

    //sdkcaller
    public static void trySetUserData(SgUserData ud) {
        Message msg = new Message();
        msg.what = MSG_SET_USER_DATA;
        msg.obj = ud;
        handler.sendMessage(msg);
    }

    //?try?
    public static void handleShowToast(String notice) {
        final String text = notice;
        Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() {
            @Override
            public void run() {
                SDKCaller.showToastNative(text);
            }
        });
    }

    //?try?
    public static void handleSetUserData(SgUserData ud) {
        final boolean cIsSuc = ud.isSuccess;
        final String cUid = ud.userId;
        final String cUname = ud.userName;
        final boolean cIsFb = ud.isFacebook;

        Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() {
            @Override
            public void run() {
                SDKCaller.setUserDataNative(cIsSuc, cUid, cUname, cIsFb);
            }
        });
    }

}