public class BaseActivity extends Activity {

    // 游戏背景音乐
    public static MusicManager musicMgr = null;
    // 游戏音效
    public static SoundManager soundMgr = null;
    // 游戏关卡配置
    public static List<ModeCfg> modeCfgs = null;
    // 游戏配置Map
    public static SparseArray<LevelCfg> levelCfgs = null;
    // 第三方登录用户信息
    public static UserInfo userInfo = null;
    // rankAdapter缓存
    public static RankAdapter[] rankAdapters = null;
    // 根据游戏皮肤缓存图片，不用每次加载
    public static List<List<Bitmap>> skinImages = new ArrayList<List<Bitmap>>(ViewSettings.SkinNames.length);
    // 缓存特定比例的卡片
    public static Map<String, List<Bitmap>> scaleImages = new HashMap<String, List<Bitmap>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initFullScreen();

        initShortcut();

        initMusic();

        initSound();
    }

    /**
     * 全屏初始化
     */
    private void initFullScreen() {
        // set full screen
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 初始化快捷键
     */
    private void initShortcut() {
        if (!CacheUtil.hasBind(this, "short_cut")) {
            ShortcutUtil util = new ShortcutUtil(this);
            util.delShortcut();
            util.addShortcut();
            CacheUtil.setBind(this, "short_cut", true);
        }
    }

    /**
     * 初始化游戏音乐
     */
    private void initMusic() {
        if (musicMgr == null) {
            musicMgr = new MusicManager(this);
        }
        playMusic();
    }

    /**
     * 播放背景音乐
     */
    protected void playMusic() {
        if (musicMgr != null) {
            musicMgr.play();
        }
    }

    /**
     * 停止播放背景音乐
     */
    protected void stopMusic() {
        if (musicMgr != null) {
            musicMgr.stop();
        }
    }

    /**
     * 初始化游戏音效
     */
    private void initSound() {
        if (soundMgr == null) {
            soundMgr = new SoundManager(BaseActivity.this);
        }
    }

    /**
     * 加载关卡配置
     */
    protected void loadCfgs() {
        if (modeCfgs == null) {
            Stopwatch sw = new Stopwatch();
            sw.start();
            XmlResourceParser xrp = getResources().getXml(R.xml.gamecfg);
            GameCfg gameCfg = new GameCfg(xrp);
            modeCfgs = gameCfg.getModeInfos();
            levelCfgs = new SparseArray<LevelCfg>();
            for (ModeCfg modeCfg : modeCfgs) {
                for (RankCfg rankCfg : modeCfg.getRankInfos()) {
                    for (LevelCfg levelCfg : rankCfg.getLevelInfos()) {
                        levelCfgs.append(levelCfg.getLevelId(), levelCfg);
                    }
                }
            }
            sw.stop();
            Log.e("loadXmlCfgs-time", String.valueOf(sw.getElapsedTime()));
        }

        // 加载全局配置
        loadGlobalCfg();

        // 加载本地关卡分数
        loadLevelScores();
    }

    /**
     * 加载全局配置
     */
    private void loadGlobalCfg() {
        String globalCfgStr = getGlobalCfg();
        if (globalCfgStr.equals("")) {
            setGlobalCfg();
        } else {
            LevelCfg.globalCfg = GlobalCfg.parse(globalCfgStr);
        }
    }

    /**
     * 加载本地关卡分数
     */
    private void loadLevelScores() {
        // 初始化数据库
        DbScore.init(this, modeCfgs);

        List<LevelScore> levelScores = DbScore.selectAll();
        for (LevelScore score : levelScores) {
            int levelId = Integer.parseInt(score.getLevel());
            LevelCfg cfg = levelCfgs.get(levelId);
            if (cfg != null) {
                cfg.setMaxScore(score.getMaxScore());
                cfg.setMinTime(score.getMinTime());
                cfg.setActive(score.getIsActive() == 1);
                cfg.setLevelStar(score.getStar());
                cfg.setUpload(score.getIsUpload() == 1);
            }
        }
    }

    /**
     * 加载rankAdapter
     */
    protected void loadRankAdapters() {
        rankAdapters = new RankAdapter[modeCfgs.size()];
        for (int i = 0; i < modeCfgs.size(); i++) {
            rankAdapters[i] = new RankAdapter(this, modeCfgs.get(i).getRankInfos());
        }
    }

    /**
     * 加载游戏皮肤
     */
    protected void loadSkinImages() {
        InputStream is = null;
        for (String skinName : ViewSettings.SkinNames) {
            String imageFile = String.format("%ss.dat", skinName);
            try {
                is = getResources().getAssets().open(imageFile);
                Bitmap bm = BitmapFactory.decodeStream(is);
                List<Bitmap> images = ImageUtil.cutImage(bm, ViewSettings.ImageXCount, ViewSettings.ImageYCount);
                if (images != null) {
                    // 加入缓存
                    skinImages.add(images);
                }
            } catch (Exception e) {
                Log.d("loadSkinImages", e.getMessage());
            }
        }

        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取全局配置字符串
     * 
     * @return 全局配置字符串
     */
    protected String getGlobalCfg() {
        return CacheUtil.getBindStr(getApplicationContext(), ViewSettings.GlobalCfgStr);
    }

    /**
     * 设置全局配置
     */
    public void setGlobalCfg() {
        CacheUtil.setBindStr(getApplicationContext(), ViewSettings.GlobalCfgStr, LevelCfg.globalCfg.toString());
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 停止背景音乐
        stopMusic();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 开启背景音乐
        playMusic();
    }

} public class ViewSettings {

    /**
     * 游戏时间消息
     */
    public final static int TimeMessage = 0x1;

    /**
     * 游戏分数消息
     */
    public final static int ScoreMessage = 0x2;

    /**
     * 游戏失败消息
     */
    public final static int FailMessage = 0x3;

    /**
     * 游戏胜利消息
     */
    public final static int WinMessage = 0x4;

    /**
     * 游戏提示消息
     */
    public final static int PromptMessage = 0x5;

    /**
     * 游戏重排消息
     */
    public final static int RefreshMessage = 0x6;

    /**
     * 用户登录消息
     */
    public static final int MSG_LOGIN = 0x11;

    /**
     * 用户取消登录消息
     */
    public static final int MSG_AUTH_CANCEL = 0x12;

    /**
     * 用户登录错误消息
     */
    public static final int MSG_AUTH_ERROR = 0x13;

    /**
     * 用户上传分数消息同时返回top3
     */
    public static final int MSG_LEVEL_ADDGET = 0x14;

    /**
     * 用户获取分数排行榜
     */
    public static final int MSG_LEVEL_GET = 0x15;

    /**
     * 网络问题
     */
    public static final int MSG_NETWORK_EXCEPTION = 0x18;

    // /**
    // * 获取用户图标
    // */
    // public static final int MSG_IMAGE_GET = 0x19;

    // /**
    // * 获取排行榜图标
    // */
    // public static final int MSG_TOPIMAGES_GET = 0x20;

    /**
     * 更新用户的钻石和金币
     */
    public static final int MSG_UPDATE_GOLD = 0x21;

    /**
     * 更新用户的点赞数
     */
    public static final int MSG_UPDATE_LIKE = 0x22;

    /**
     * 登录分享提示
     */
    public static final int MSG_LOGIN_PROMPT = 0x23;

    /**
     * 每种皮肤的图片X数量
     */
    public static int ImageXCount = 4;

    /**
     * 每种皮肤的图片Y数量
     */
    public static int ImageYCount = 4;

    /**
     * 最大的提示数
     */
    public static int PromptMaxNum = 10;

    /**
     * 最大的重排数
     */
    public static int RefreshMaxNum = 10;

    /**
     * 最大的重排数
     */
    public static int AddTimeMaxNum = 10;

    /**
     * 增加时间的秒数
     */
    public static int AddTimeSeconds = 5;

    /**
     * 排行榜图像宽度
     */
    public static int TopImageWidth = 50;

    /**
     * 用户图像宽度
     */
    public static int UserImageWidth = 60;

    /**
     * 昵称显示长度
     */
    public static int ShowNameLength = 11;

    /**
     * 每次取排行榜前3名
     */
    public static int TopN = 3;

    /**
     * 排行榜查询取前十
     */
    public static int TopRankN = 10;

    /**
     * 分享奖励钻石数
     */
    public static int ShareReward = 20;

    /**
     * 网站的域名根目录
     */
    public static String WebRoot = "http://xxllk.aliapp.com";

    /**
     * 阿里ACE无法发送推送
     */
    public static String LikeWebRoot = "http://182.92.83.63:9080/linkupweb";

    /**
     * 数据缓存版本字符串
     */
    public static String CacheVersion = "140";

    /**
     * 全局配置的 Shared Preference
     */
    public static String GlobalCfgStr = "globalcfg_" + CacheVersion;

    /**
     * 点赞用户的 Shared Preference
     */
    public static String LikeUsersStr = "likeusers";

    /**
     * 本地数据库文件名
     */
    public static String DbFileName = "data" + CacheVersion + ".db";

    /**
     * 本地数据库的版本
     */
    public static int DbVersion = 2;

    /**
     * 初始激活的关卡，按升序排列
     */
    public static int[] DefaultActiveLevels = new int[] { 0, 1, 2, 3, 24, 25, 26, 27, 48, 49, 50, 51, 120, 121, 122, 123, 192, 193, 194, 195, 264, 265, 266,
            267, 336, 337, 338, 339 };

    /**
     * 两次back退出间的间隔
     */
    public static int TwoBackExitInterval = 2000;

    /**
     * 数字图片
     */
    public static int[] Numbers = new int[] { R.drawable.n0, R.drawable.n1, R.drawable.n2, R.drawable.n3, R.drawable.n4, R.drawable.n5, R.drawable.n6,
            R.drawable.n7, R.drawable.n8, R.drawable.n9, R.drawable.n10, R.drawable.n11, R.drawable.n12, R.drawable.n13, R.drawable.n14, R.drawable.n15,
            R.drawable.n16, R.drawable.n17, R.drawable.n18, R.drawable.n19, R.drawable.n20, R.drawable.n21, R.drawable.n22, R.drawable.n23, R.drawable.n24 };

    /**
     * 游戏背景图片
     */
    public static int[] GameBgImageIds = new int[] { R.drawable.p2, R.drawable.p3, R.drawable.p4, R.drawable.p5, R.drawable.p6 };

    /**
     * 游戏级别背景颜色
     */
    public static int[] RankBgColors = new int[] { R.color.rankbg_color1, R.color.rankbg_color2, R.color.rankbg_color3, R.color.rankbg_color4,
            R.color.rankbg_color5 };

    /**
     * 游戏评级
     */
    public static int[] StarImages = new int[] { R.drawable.star1, R.drawable.star2, R.drawable.star3 };

    /**
     * 五套皮肤的名称
     */
    public static String[] SkinNames = new String[] { "classic", "fruit", "pet", "fish", "farm" };

    /**
     * 模式下面的等级数组
     */
    public static int[] ModeRanks = new int[] { R.array.totalranks, R.array.mode0ranks, R.array.mode1ranks, R.array.mode2ranks, R.array.mode3ranks,
            R.array.mode4ranks };

    /**
     * 排行榜名次
     */
    public static int[] TopOrderImages = new int[] { R.drawable.top_1, R.drawable.top_2, R.drawable.top_3, R.drawable.top_4, R.drawable.top_5,
            R.drawable.top_6, R.drawable.top_7, R.drawable.top_8, R.drawable.top_9, R.drawable.top_10, };

    /**
     * 填写从短信SDK应用后台注册得到的APPKEY
     */
    public static String APPKEY = "25c23a360539";

    /**
     * 填写从短信SDK应用后台注册得到的APPSECRET
     */
    public static String APPSECRET = "d224092cafca6db2b5a942d0d298ba92";

    /**
     * 91发布包，不允许弹出框
     */
    public static String Deploy91 = "Deploy91";

    /**
     * 360发布包，不允许第三方登录
     */
    public static String Deploy360 = "Deploy360";

    /**
     * 其它发布包
     */
    public static String DeployOther = "DeployOther";

    /**
     * 部署方式
     */
    public static String DeployType = DeployOther;

} public class WelcomeActivity extends BaseActivity implements OnClickListener, IUpload {

    private long exitTime = 0;
    private TextView ivMusic = null;
    private TextView ivSound = null;
    private LevelTop levelTop = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_welcome);

        initClickListener();

        initMusicSetting();

        initSoundSetting();

        initLogin();

        initSDK();

        if (ViewSettings.DeployType == ViewSettings.Deploy91 || ViewSettings.DeployType == ViewSettings.Deploy360) {
        } else {
            initInfoDialog();
        }

        // 异步加载配置信息
        new LoadCfgTask().execute();

        // initNotice();

        startAnimation();
    }

    // /**
    // * 初始化公告
    // */
    // private void initNotice() {
    // final String[] NoticeMsg = getString(R.string.notice).split("@");
    // Display mDisplay = getWindowManager().getDefaultDisplay();
    // Point size = new Point();
    // mDisplay.getSize(size);
    // tsNotice = (TextView) findViewById(R.id.tsNotice);
    // tsNotice.setTextSize(16);
    // tsNotice.setTextColor(0xffff6347);
    // tsNotice.setGravity(Gravity.CENTER);
    // noticeAnim = ObjectAnimator.ofFloat(tsNotice, "translationX", size.x, 0);
    // noticeAnim.addListener(new AnimatorListener() {
    //
    // @Override
    // public void onAnimationCancel(Animator animation) {
    //
    // }
    //
    // @Override
    // public void onAnimationEnd(Animator animation) {
    // noticeIndex++;
    // if (noticeIndex > NoticeMsg.length - 1) {
    // noticeIndex = 0;
    // }
    // animation.start();
    // }
    //
    // @Override
    // public void onAnimationRepeat(Animator animation) {
    //
    // }
    //
    // @Override
    // public void onAnimationStart(Animator animation) {
    // tsNotice.setText(NoticeMsg[noticeIndex]);
    // }
    // });
    // noticeAnim.setDuration(2000);
    // noticeAnim.setStartDelay(5000);
    // noticeAnim.start();
    // }

    private void initLogin() {
        levelTop = (LevelTop) findViewById(R.id.welcome_user);
        levelTop.setUploadListener(this);
        levelTop.reset();
        if (ViewSettings.DeployType == ViewSettings.Deploy360) {
            levelTop.setVisibility(View.GONE);
        }
    }

    private void initClickListener() {
        findViewById(R.id.mode0).setOnClickListener(this);
        findViewById(R.id.mode1).setOnClickListener(this);
        findViewById(R.id.mode2).setOnClickListener(this);
        findViewById(R.id.mode3).setOnClickListener(this);
        findViewById(R.id.mode4).setOnClickListener(this);

        findViewById(R.id.music).setOnClickListener(this);
        findViewById(R.id.sound).setOnClickListener(this);
        findViewById(R.id.top).setOnClickListener(this);
        findViewById(R.id.friend).setOnClickListener(this);
        findViewById(R.id.about).setOnClickListener(this);
    }

    @Override
    protected void playMusic() {
        if (musicMgr != null) {
            musicMgr.setBgMusicRes(R.raw.welcomebg);
            musicMgr.play();
        }
    }

    /**
     * 初始化背景音乐设置
     */
    private void initMusicSetting() {
        ivMusic = (TextView) findViewById(R.id.music);
        setGameMusic();
        if (musicMgr != null) {
            musicMgr.setBgMisicEnabled(LevelCfg.globalCfg.isGameBgMusic());
        }
    }

    /**
     * 初始化音效设置
     */
    private void initSoundSetting() {
        ivSound = (TextView) findViewById(R.id.sound);
        setGameSound();
        if (soundMgr != null) {
            soundMgr.setSoundEnabled(LevelCfg.globalCfg.isGameSound());
        }
    }

    /**
     * 设置游戏背景音乐
     */
    private void setGameMusic() {
        if (LevelCfg.globalCfg.isGameBgMusic()) {
            Drawable drawable = getResources().getDrawable(R.drawable.music);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            ivMusic.setCompoundDrawables(null, drawable, null, null);
        } else {
            Drawable drawable = getResources().getDrawable(R.drawable.music_d);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            ivMusic.setCompoundDrawables(null, drawable, null, null);
        }
    }

    /**
     * 设置游戏音效
     */
    private void setGameSound() {
        if (LevelCfg.globalCfg.isGameSound()) {
            Drawable drawable = getResources().getDrawable(R.drawable.sound);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            ivSound.setCompoundDrawables(null, drawable, null, null);
        } else {
            Drawable drawable = getResources().getDrawable(R.drawable.sound_d);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            ivSound.setCompoundDrawables(null, drawable, null, null);
        }
    }

    /**
     * 初始化标题动画
     */
    private void startAnimation() {
        GameTitle gameTitle = (GameTitle) findViewById(R.id.gameTitle);
        gameTitle.startAnimation();

        // if (noticeAnim != null && !noticeAnim.isRunning()) {
        // noticeAnim.start();
        // }
    }

    /**
     * 反初始化标题动画
     */
    private void stopAnimation() {
        GameTitle gameTitle = (GameTitle) findViewById(R.id.gameTitle);
        gameTitle.stopAnimation();

        // if (noticeAnim != null && noticeAnim.isRunning()) {
        // noticeAnim.cancel();
        // }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopAnimation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startAnimation();
        if (userInfo != null && levelTop != null) {
            levelTop.updateUserInfo();
        }
    }

    /**
     * 处理home或者back键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            if ((System.currentTimeMillis() - exitTime) > ViewSettings.TwoBackExitInterval) {
                ToastUtil.getToast(this, R.string.back_again).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.mode0:
        case R.id.mode1:
        case R.id.mode2:
        case R.id.mode3:
        case R.id.mode4:
            soundMgr.select();
            int modeIndex = Integer.parseInt((String) v.getTag());

            if (ViewSettings.DeployType == ViewSettings.Deploy91 || ViewSettings.DeployType == ViewSettings.Deploy360) {
            } else {
                // 星星模式需要提示登录
                if (modeIndex == 4 && BaseActivity.userInfo == null) {
                    HelpDialog helper = new HelpDialog(this);
                    helper.setTitle(getString(R.string.info_prompt));
                    helper.setMessage(getString(R.string.xxlogin_prompt));
                    helper.setLinkVisible(false);
                    helper.show();
                }
            }
            if (modeIndex >= 0) {
                Intent intent = new Intent(this, RankActivity.class);
                intent.putExtra("modeIndex", modeIndex);
                startActivity(intent);
            }
            break;
        case R.id.music: {
            if (musicMgr != null) {
                musicMgr.setBgMisicEnabled(!musicMgr.isBgMisicEnabled());
                // 保存全局设置--背景音乐
                setGlobalCfg();
                setGameMusic();
            }
        }
            break;
        case R.id.sound: {
            if (soundMgr != null) {
                soundMgr.setSoundEnabled(!soundMgr.isSoundEnabled());
                // 保存全局设置--音效
                setGlobalCfg();
                setGameSound();
            }
        }
            break;
        case R.id.top: {
            Intent intent = new Intent(this, TopActivity.class);
            startActivity(intent);
        }
            break;
        case R.id.about: {
            HelpDialog helper = new HelpDialog(this);
            helper.setTitle(getString(R.string.about));
            helper.setMessage(getString(R.string.about_info));
            helper.show();
        }
            break;
        case R.id.friend: {
            // 打开通信录好友列表页面
            ContactsPage contactsPage = new ContactsPage();
            contactsPage.show(this);
        }
            break;
        }
    }

    @Override
    protected void onDestroy() {
        try {
            ShareSDK.stopSDK(this);
        } catch (Exception ex) {
        }

        super.onDestroy();
    }

    @Override
    public void onLoginSuccess(Message msg) {
        if (userInfo != null) {
            // 加载用户信息
            levelTop.loadUserInfo();
        }
    }

    @Override
    public void onLevelResultAdd(Message msg) {
    }

    /**
     * 初始化第三方sdk
     */
    private void initSDK() {
        try {
            ShareSDK.initSDK(this);
        } catch (Exception ex) {
            Log.d("ShareSDK", ex.getMessage());
        }

        try {
            // 初始化短信SDK
            SMSSDK.initSDK(this, ViewSettings.APPKEY, ViewSettings.APPSECRET);
        } catch (Exception ex) {
            Log.d("SMSSDK", ex.getMessage());
        }

        try {
            XiaomiUpdateAgent.setCheckUpdateOnlyWifi(true);
            XiaomiUpdateAgent.update(this);
        } catch (Exception ex) {
            Log.d("XiaomiUpdate", ex.getMessage());
        }
    }

    /**
     * 初始化提示框
     */
    private void initInfoDialog() {
        if (!CacheUtil.hasBind(this, "info_login")) {
            InfoDialog info = new InfoDialog(this);
            info.setPositiveButton("info_login");
            info.setWeiboClick(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    levelTop.weiboClick();
                }
            });
            info.setQQClick(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    levelTop.qqClick();
                }
            });
            info.show();
        }
    }

    /**
     * 加载配置的异步任务
     * 
     * @author yzb
     * 
     */
    private class LoadCfgTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // 加载配置信息
            loadCfgs();

            // 加载关卡适配器
            loadRankAdapters();

            // 加载图片信息
            loadSkinImages();

            return null;
        }
    }
} public interface IUpload {
    /**
     * 点击验证时的处理
     */
//    void onAuthorizeClick();

    /**
     * 登录成功后的处理
     * 
     * @param msg
     *            登录信息
     */
    void onLoginSuccess(Message msg);

    /**
     * 上传关卡分数和时间后的处理
     * 
     * @param msg
     *            消息
     */
    void onLevelResultAdd(Message msg);
} public class UserInfo {

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserGender() {
        return userGender;
    }

    public void setUserGender(String userGender) {
        this.userGender = userGender;
    }

    public String getUserIcon() {
        return userIcon;
    }

    public void setUserIcon(String userIcon) {
        this.userIcon = userIcon;
    }

    public int getDiamond(Context context) {
        String d = CacheUtil.getBindStr(context, userId + "_diamond");
        if (d == null || d.equals("")) {
            return 0;
        } else {
            return Integer.parseInt(d);
        }
    }

    public void setDiamond(Context context, int diamond) {
        CacheUtil.setBindStr(context, userId + "_diamond", String.valueOf(diamond));
    }

    public void addDiamond(Context context, int addDiamond) {
        CacheUtil.setBindStr(context, userId + "_diamond", String.valueOf(getDiamond(context) + (addDiamond)));
    }

    public int getGold(Context context) {
        String d = CacheUtil.getBindStr(context, userId + "_gold");
        if (d == null || d.equals("")) {
            return 0;
        } else {
            return Integer.parseInt(d);
        }
    }

    public void setGold(Context context, int gold) {
        CacheUtil.setBindStr(context, userId + "_gold", String.valueOf(gold));
    }

    public void addGold(Context context, int addGold) {
        CacheUtil.setBindStr(context, userId + "_gold", String.valueOf(getGold(context) + (addGold)));
    }

    public boolean isAward() {
        return isAward;
    }

    public void setAward(boolean isAward) {
        this.isAward = isAward;
    }

    public Bitmap getUserImage() {
        return userImage;
    }

    public void setUserImage(Bitmap userImage) {
        this.userImage = userImage;
    }

    public int getTotalRank() {
        return totalRank;
    }

    public void setTotalRank(int totalRank) {
        this.totalRank = totalRank;
    }

    public int getTop1Levels() {
        return top1Levels;
    }

    public void setTop1Levels(int top1Levels) {
        this.top1Levels = top1Levels;
    }

    public int getLike() {
        return like;
    }

    public void setLike(int like) {
        this.like = like;
    }

    private String userId;
    private String userName;
    private String userGender;
    private String userIcon;
    private boolean isAward = false;
    private Bitmap userImage;
    private int totalRank;
    private int top1Levels;
    private int like;
} public class UserScore {
    private static String USER_ADD_URI = ViewSettings.WebRoot + "/webapi/user/add";
    private static String USER_UPDATE_URI = ViewSettings.WebRoot + "/webapi/user/update";
    private static String USER_LIKE_URI = ViewSettings.LikeWebRoot + "/webapi/user/like";
    public static String USER_TOTALRANK_URI = ViewSettings.WebRoot + "/webapi/user/totalrank";
    public static String LEVEL_ADD_URI = ViewSettings.WebRoot + "/webapi/level/add";
    public static String LEVEL_GET_URI = ViewSettings.WebRoot + "/webapi/level/get";
    public static String LEVEL_ADDGET_URI = ViewSettings.WebRoot + "/webapi/level/addget";

    /**
     * 记录用户登录
     * 
     * @param userInfo
     *            用户登录信息
     * @param handler
     *            消息处理
     */
    public static void login(final UserInfo userInfo, final Handler handler) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("userid", userInfo.getUserId()));
        params.add(new BasicNameValuePair("username", userInfo.getUserName()));
        params.add(new BasicNameValuePair("usergender", userInfo.getUserGender()));
        params.add(new BasicNameValuePair("usericon", userInfo.getUserIcon()));
        if (!StringUtil.isNullOrEmpty(MyApplication.Push_Reg_ID)) {
            params.add(new BasicNameValuePair("regid", MyApplication.Push_Reg_ID));
        }
        new Thread(new Runnable() {

            @Override
            public void run() {
                String result = RestUtil.post(USER_ADD_URI, params);
                if (result != null) {
                    Message msg = new Message();
                    msg.what = ViewSettings.MSG_LOGIN;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } else {
                    // 网络或其它问题
                    handler.sendEmptyMessage(ViewSettings.MSG_NETWORK_EXCEPTION);
                }
            }
        }).start();
    }

    /**
     * 更新用户的钻石和金币
     * 
     * @param userId
     *            用户ID
     * @param diamond
     *            改变的钻石数
     * @param gold
     *            改变的金币数
     * @param handler
     *            消息处理
     */
    public static void updateAward(final String userId, int diamond, int gold, final Handler handler) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("userid", userId));
        params.add(new BasicNameValuePair("diamond", String.valueOf(diamond)));
        params.add(new BasicNameValuePair("gold", String.valueOf(gold)));
        new Thread(new Runnable() {

            @Override
            public void run() {
                String result = RestUtil.post(USER_UPDATE_URI, params);
                if (result != null) {
                    Message msg = new Message();
                    msg.what = ViewSettings.MSG_UPDATE_GOLD;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } else {
                    // 网络或其它问题
                    handler.sendEmptyMessage(ViewSettings.MSG_NETWORK_EXCEPTION);
                }
            }
        }).start();
    }

    /**
     * 点赞用户
     * 
     * @param tag
     *            用户ID;用户名
     * @param likeNum
     *            1:赞;-1:取消赞
     * @param handler
     */
    public static void updateLike(final String tag, final int likeNum, final Handler handler) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        String userId = tag.substring(0, tag.indexOf(";"));
        params.add(new BasicNameValuePair("userid", userId));
        params.add(new BasicNameValuePair("like", String.valueOf(likeNum)));
        new Thread(new Runnable() {

            @Override
            public void run() {
                String result = RestUtil.post(USER_LIKE_URI, params);
                if (result != null) {
                    Message msg = new Message();
                    msg.what = ViewSettings.MSG_UPDATE_LIKE;
                    msg.obj = String.valueOf(likeNum) + ";" + tag;
                    handler.sendMessage(msg);
                } else {
                    // 网络或其它问题
                    handler.sendEmptyMessage(ViewSettings.MSG_NETWORK_EXCEPTION);
                }
            }
        }).start();
    }

    /**
     * 新增用户关卡分数，用于排名
     * 
     * @param levelInfo
     *            上传的分数信息
     * @param handler
     *            消息处理
     */
    public static void addGetResult(LevelInfo levelInfo, final Handler handler) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("userid", levelInfo.getUserId()));
        params.add(new BasicNameValuePair("level", String.valueOf(levelInfo.getLevel())));
        params.add(new BasicNameValuePair("score", String.valueOf(levelInfo.getScore())));
        params.add(new BasicNameValuePair("time", String.valueOf(levelInfo.getTime())));
        params.add(new BasicNameValuePair("diamond", String.valueOf(levelInfo.getDiamond())));
        params.add(new BasicNameValuePair("gold", String.valueOf(levelInfo.getGold())));
        new Thread(new Runnable() {

            @Override
            public void run() {
                String result = RestUtil.post(LEVEL_ADDGET_URI, params);
                if (result != null) {
                    // 成功获取排名信息
                    Message msg = new Message();
                    msg.what = ViewSettings.MSG_LEVEL_ADDGET;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } else {
                    // 网络或其它问题
                    handler.sendEmptyMessage(ViewSettings.MSG_NETWORK_EXCEPTION);
                }
            }
        }).start();
    }

    /**
     * 按关卡获取排名信息
     * 
     * @param level
     *            关卡id
     * @param handler
     *            消息处理
     */
    public static void getLevelTops(int level, final Handler handler) {
        getLevelTops(level, ViewSettings.TopN, handler);
    }

    /**
     * 按关卡获取排名信息
     * 
     * @param level
     *            关卡id
     * @param handler
     *            消息处理
     */
    public static void getLevelTops(int level, int topN, final Handler handler) {
        final String uri = LEVEL_GET_URI + "?level=" + String.valueOf(level) + "&top=" + String.valueOf(topN);
        new Thread(new Runnable() {

            @Override
            public void run() {
                String result = RestUtil.get(uri);
                if (result != null) {
                    // 成功获取排名信息
                    Message msg = new Message();
                    msg.what = ViewSettings.MSG_LEVEL_GET;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } else {
                    // 网络或其它问题
                    handler.sendEmptyMessage(ViewSettings.MSG_NETWORK_EXCEPTION);
                }
            }
        }).start();
    }

    // /**
    // * 获取用户icon
    // *
    // * @param url
    // * url地址
    // * @param handler
    // * 消息处理
    // */
    // public static void getUserImage(final String url, final Handler handler) {
    // new Thread(new Runnable() {
    //
    // @Override
    // public void run() {
    // String newUrl = url;
    // // 获取清晰的QQ图像
    // // if(newUrl.endsWith("/30")){
    // // newUrl = newUrl.substring(0, newUrl.length() - 3) + "/100";
    // // }
    // Bitmap bm = IconCacheUtil.getIcon(newUrl);
    // if (bm == null) {
    // try {
    // bm = BitmapFactory.decodeStream((new URL(newUrl)).openStream());
    // } catch (Exception e) {
    // e.printStackTrace();
    // bm = null;
    // }
    // }
    // if (bm != null) {
    // IconCacheUtil.putIcon(newUrl, bm);
    // // 成功获取排名信息
    // Message msg = new Message();
    // msg.what = ViewSettings.MSG_IMAGE_GET;
    // msg.obj = bm;
    // handler.sendMessage(msg);
    // } else {
    // // 网络或其它问题
    // handler.sendEmptyMessage(ViewSettings.MSG_NETWORK_EXCEPTION);
    // }
    // }
    // }).start();
    // }
} public class VolleyHelper {

    private Context ctx = null;
    private RequestQueue requestQueue = null;

    public VolleyHelper(Context ctx) {
        this.ctx = ctx;
        requestQueue = Volley.newRequestQueue(ctx);
    }

    /**
     * 加载JsonArray数据
     * 
     * @param url
     *            url地址
     * @param listener
     *            网络消息处理监听器
     */
    public void getJsonArray(String url, final NetMsgListener<JSONArray> listener) {

        JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                if (listener != null) {
                    listener.onNetMsg(response);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError e) {
                if (listener != null) {
                    listener.onError(e);
                }
            }
        });
        requestQueue.add(jsonObjectRequest);
    }

    public void getString(String url, final NetMsgListener<String> listener) {

        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (listener != null) {
                    listener.onNetMsg(response);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError e) {
                if (listener != null) {
                    listener.onError(e);
                }
            }
        });
        requestQueue.add(stringRequest);
    }

    /**
     * 加载网络图片到ImageView
     * 
     * @param iv
     *            ImageView实例
     * @param url
     *            url地址
     */
    public void loadImage(ImageView iv, String url) {
        ImageLoader imageLoader = new ImageLoader(requestQueue, new BitmapCache());
        ImageListener listener = ImageLoader.getImageListener(iv, R.drawable.icon_default, R.drawable.icon_default);
        imageLoader.get(url, listener);
    }

    /**
     * 加载网络图片到NetworkImageView
     * 
     * @param niv
     *            NetworkImageView实例
     * @param url
     *            url地址
     */
    public void loadNetImage(NetworkImageView niv, String url) {
        ImageLoader imageLoader = new ImageLoader(requestQueue, new BitmapCache());

        niv.setTag("url");
        niv.setImageUrl(url, imageLoader);
    }

    /**
     * 取消所有请求
     */
    public void cancelAll() {
        requestQueue.cancelAll(ctx);
    }
} public class LevelUtil {

    /**
     * 是否是时间模式
     * 
     * @param level
     *            关卡序号
     * @return 时间模式:true
     */
    public static boolean isTimeMode(int level) {
        return (level >= 120 && level < 192) || (level >= 264 && level < 408);
    }
} public class StringUtil {

    /**
     * 判断null或者空
     * 
     * @param str
     *            字符串
     * @return
     */
    public static boolean isNullOrEmpty(String str) {
        return str == null || str.equals("");
    }

    /**
     * 转为UTF-8编码
     * 
     * @param str
     *            字符串
     * @return utf-8编码字符串
     */
    public static String toUtf8(String str) {
        try {
            return new String(str.getBytes("ISO8859_1"), "UTF-8");
        } catch (Exception e) {
            Log.d("StringUtil-toUtf8", e.getMessage());
            return str;
        }
    }

    /**
     * 将时间秒数转化为格式mm:ss
     * 
     * @param seconds
     *            时间秒数
     * @return 时间格式字符串
     */
    public static String secondToString(int seconds) {
        int min = seconds / 60;
        int second = seconds % 60;

        StringBuffer sb = new StringBuffer();
        if (min > 9) {
            sb.append(String.valueOf(min));
        } else {
            sb.append("0" + String.valueOf(min));
        }

        if (second > 9) {
            sb.append(":" + String.valueOf(second));
        } else {
            sb.append(":0" + String.valueOf(second));
        }

        return sb.toString();
    }

    public static String substring(String str, int toCount) {
        return substring(str, toCount, "..");
    }

    /**
     * 获取符合长度的字符串
     * 
     * @param str
     *            需要控制长度的字符串
     * @param toCount
     *            长度
     * @param more
     *            超过长度字符
     * @return 符合长度的字符串
     */
    public static String substring(String str, int len, String more) {
        if (str == null || "".equals(str) || len < 1) {
            return "";
        }
        char[] chars = str.toCharArray();
        int count = 0;
        int charIndex = 0;
        for (int i = 0; i < chars.length; i++) {
            int charLength = getCharLen(chars[i]);
            if (count <= len - charLength) {
                count += charLength;
                charIndex++;
            } else {
                break;
            }
        }
        if (charIndex == chars.length) {
            return new String(chars, 0, charIndex);
        } else {
            return new String(chars, 0, charIndex) + more;
        }
    }

    /**
     * 获取字符长度
     * 
     * @param c
     *            字符
     * @return 长度
     */
    private static int getCharLen(char c) {
        int k = 0x80;
        return c / k == 0 ? 1 : 2;
    }
} public interface ILoadImage {
    void onCircleImageLoaded(Bitmap bm);
}
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qzone.QZone;
import com.znv.linkup.BaseActivity;
import com.znv.linkup.R;
import com.znv.linkup.ViewSettings;
import com.znv.linkup.WelcomeActivity;
import com.znv.linkup.rest.IUpload;
import com.znv.linkup.rest.UserInfo;
import com.znv.linkup.rest.UserScore;
import com.znv.linkup.rest.VolleyHelper;
import com.znv.linkup.util.LevelUtil;
import com.znv.linkup.util.StringUtil;
import com.znv.linkup.view.CircleImageView.ILoadImage;
        holder.tvthirdscore.setText("");
        holder.ivthirdIcon.setImageResource(R.drawable.icon_default);
        holder.ivIcon.setImageResource(R.drawable.icon_default);
        holder.tvUser.setText("");
    }

    public void onComplete(Platform plat, int action, HashMap<String, Object> res) {
        if (action == Platform.ACTION_USER_INFOR) {
            login(plat);
        }
    }

    public void onError(Platform platform, int action, Throwable t) {
        if (action == Platform.ACTION_USER_INFOR) {
            netMsgHandler.sendEmptyMessage(ViewSettings.MSG_AUTH_ERROR);
        }
    }

    public void onCancel(Platform platform, int action) {
        if (action == Platform.ACTION_USER_INFOR) {
            netMsgHandler.sendEmptyMessage(ViewSettings.MSG_AUTH_CANCEL);
        }
    }

    /**
     * 处理网络消息回调的handler
     */
    @SuppressLint("HandlerLeak")
    public Handler netMsgHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case ViewSettings.MSG_LEVEL_ADDGET: {
                showLevelTop(msg);
                if (uploadListener != null) {
                    uploadListener.onLevelResultAdd(msg);
                }
            }
                break;
            case ViewSettings.MSG_LEVEL_GET:
                showLevelTop(msg);
                break;
            case ViewSettings.MSG_LOGIN: {
                try {
                    JSONObject json = new JSONObject((String) msg.obj);
                    UserInfo userInfo = new UserInfo();
                    userInfo.setUserId(json.getString("userId"));
                    userInfo.setUserName(json.getString("userName"));
                    userInfo.setUserGender(json.getString("userGender"));
                    userInfo.setUserIcon(json.getString("userIcon"));
                    userInfo.setDiamond(getContext(), json.getInt("diamond"));
                    userInfo.setGold(getContext(), json.getInt("gold"));
                    userInfo.setAward(json.getInt("isAward") == 1);
                    userInfo.setTotalRank(json.getInt("totalRank"));
                    userInfo.setTop1Levels(json.getInt("top1Levels"));
                    userInfo.setLike(json.getInt("like"));

                    BaseActivity.userInfo = userInfo;
                    msg.obj = userInfo;
                    if (uploadListener != null) {
                        uploadListener.onLoginSuccess(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
                break;
            // case ViewSettings.MSG_IMAGE_GET: {
            // Bitmap bm = (Bitmap) msg.obj;
            // if (bm != null) {
            // showStatus(LevelTopStatus.UserInfo);
            //
            // Bitmap bmRound = ImageUtil.roundBitmap(ImageUtil.scaleBitmap(bm, ViewSettings.UserImageWidth, ViewSettings.UserImageWidth));
            // WelcomeActivity.userInfo.setUserImage(bmRound);
            // holder.ivIcon.setImageBitmap(bmRound);
            // if (WelcomeActivity.userInfo != null) {
            // holder.tvUser.setText(WelcomeActivity.userInfo.getUserName() + getContext().getString(R.string.user_hello));
            // holder.tvDiamond.setText(String.valueOf(WelcomeActivity.userInfo.getDiamond(getContext())));
            // holder.tvGold.setText(String.valueOf(WelcomeActivity.userInfo.getGold(getContext())));
            // if (WelcomeActivity.userInfo.getTotalRank() == 0) {
            // holder.tvTotalRank.setText(getResources().getString(R.string.total_rank_0));
            // } else {
            // holder.tvTotalRank.setText(String.valueOf(WelcomeActivity.userInfo.getTotalRank()));
            // }
            // holder.tvTop1Levels.setText(String.valueOf(WelcomeActivity.userInfo.getTop1Levels()));
            // holder.tvLike.setText(String.valueOf(WelcomeActivity.userInfo.getLike()));
            // String text = getContext().getString(R.string.logining);
            // if (WelcomeActivity.userInfo.isAward()) {
            // text = getContext().getString(R.string.login_award);
            // }
            // Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
            // }
            // }
            // }
            // break;
            case ViewSettings.MSG_AUTH_CANCEL: {
                showStatus(LevelTopStatus.Login);
                Toast.makeText(getContext(), R.string.auth_cancel, Toast.LENGTH_SHORT).show();
            }
                break;
            case ViewSettings.MSG_AUTH_ERROR: {
                showStatus(LevelTopStatus.Login);
                Toast.makeText(getContext(), R.string.auth_error, Toast.LENGTH_SHORT).show();
            }
                break;
            case ViewSettings.MSG_NETWORK_EXCEPTION: {
                showStatus(LevelTopStatus.Login);
                Toast.makeText(getContext(), R.string.network_exception, Toast.LENGTH_SHORT).show();
            }
                break;
            }
        }

    };

    /**
     * 加载用户信息
     */
    public void loadUserInfo() {

        if (WelcomeActivity.userInfo != null) {