com.feytuo.chat.activity.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.feytuo.chat.activity.MainActivity.java

Source

/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.feytuo.chat.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

import com.easemob.chat.ConnectionListener;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.EMMessage.Type;
import com.easemob.chat.EMNotifier;
import com.easemob.chat.GroupChangeListener;
import com.easemob.chat.TextMessageBody;
import com.easemob.util.HanziToPinyin;
import com.easemob.util.NetUtils;
import com.feytuo.chat.Constant;
import com.feytuo.chat.db.InviteMessgeDao;
import com.feytuo.chat.db.UserDao;
import com.feytuo.chat.domain.InviteMessage;
import com.feytuo.chat.domain.InviteMessage.InviteMesageStatus;
import com.feytuo.chat.domain.User;
import com.feytuo.chat.utils.CommonUtils;
import com.feytuo.laoxianghao.App;
import com.feytuo.laoxianghao.PublishActivity;
import com.feytuo.laoxianghao.R;
import com.feytuo.laoxianghao.WelcomeActivity;
import com.feytuo.laoxianghao.domain.LXHUser;
import com.feytuo.laoxianghao.fragment.FindFragment;
import com.feytuo.laoxianghao.fragment.MainFragment;
import com.feytuo.laoxianghao.global.Global;
import com.feytuo.laoxianghao.share_sina.Share_Weibo;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.umeng.analytics.MobclickAgent;

/**
 * ?
 * 
 * @author feytuo
 * 
 */
public class MainActivity extends FragmentActivity implements IWeiboHandler.Response {

    public static final String TAG = "MainActivity";
    private Button[] mTabs;
    public ChatAndContactFragment cacFragment;// ?
    private SettingsFragment settingFragment;// 
    private Fragment mainFragment;// ?
    private FindFragment findFragment;// ?
    private Fragment[] fragments;
    private int index;
    // ?fragmentindex
    private int currentTabIndex;
    private NewMessageBroadcastReceiver msgReceiver;
    private Share_Weibo shareWeibo;
    // ?
    private boolean isConflict = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        shareWeibo = new Share_Weibo(this);
        ((App) getApplication()).setMainActivity(this);
        initShare(savedInstanceState);
        initView(savedInstanceState);
        inviteMessgeDao = new InviteMessgeDao(this);
        userDao = new UserDao(this);

        if (App.isLogin()) {
            registerHXListeners();
        }
    }

    // ??
    public void registerHXListeners() {
        // ?BroadcastReceiver
        Log.i(TAG, "?");
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);

        // ack?BroadcastReceiver
        IntentFilter ackMessageIntentFilter = new IntentFilter(
                EMChatManager.getInstance().getAckMessageBroadcastAction());
        ackMessageIntentFilter.setPriority(3);
        registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

        // ?BroadcastReceiver
        // IntentFilter offlineMessageIntentFilter = new
        // IntentFilter(EMChatManager.getInstance()
        // .getOfflineMessageBroadcastAction());
        // registerReceiver(offlineMessageReceiver, offlineMessageIntentFilter);

        // setContactListener???
        EMContactManager.getInstance().setContactListener(new MyContactListener());
        // ??listener
        EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
        // ?listener
        EMGroupManager.getInstance().addGroupChangeListener(new MyGroupChangeListener());
        // sdkUI ??receiverlistener, ??broadcast
        EMChat.getInstance().setAppInited();
    }

    private void initShare(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        if (savedInstanceState != null) {
            shareWeibo.getmWeiboShareAPI().handleWeiboResponse(getIntent(), this);
        }
    }

    public void onTabpublishClicked(View view) {
        if (App.isLogin()) {
            Intent intentpublish = new Intent();
            intentpublish.setClass(MainActivity.this, PublishActivity.class);
            startActivity(intentpublish);
        }
    }

    /**
     * ?
     * @param savedInstanceState 
     */
    private void initView(Bundle savedInstanceState) {
        mTabs = new Button[4];
        mTabs[0] = (Button) findViewById(R.id.btn_main_invitation);
        mTabs[1] = (Button) findViewById(R.id.btn_find);
        mTabs[2] = (Button) findViewById(R.id.btn_address_list);
        mTabs[3] = (Button) findViewById(R.id.btn_setting);
        // tab?
        mTabs[0].setSelected(true);

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        // ?
        if (savedInstanceState == null) {
            mainFragment = new MainFragment();
            // ?
            findFragment = new FindFragment();
            // ?fragment
            cacFragment = new ChatAndContactFragment();
            // fragment
            settingFragment = new SettingsFragment();
            transaction.add(R.id.fragment_container, mainFragment, "mainFragment");
            transaction.add(R.id.fragment_container, findFragment, "findFragment");
            transaction.add(R.id.fragment_container, cacFragment, "cacFragment");
            transaction.add(R.id.fragment_container, settingFragment, "settingFragment");
            //         Log.i(TAG, "------> new mainFragment:"+mainFragment);
        } else {
            mainFragment = manager.findFragmentByTag("mainFragment");
            findFragment = (FindFragment) manager.findFragmentByTag("findFragment");
            cacFragment = (ChatAndContactFragment) manager.findFragmentByTag("cacFragment");
            settingFragment = (SettingsFragment) manager.findFragmentByTag("settingFragment");
            //         Log.i(TAG, "------> old mainFragment:"+mainFragment);
        }

        fragments = new Fragment[] { mainFragment, findFragment, cacFragment, settingFragment };
        // fragment
        transaction.hide(cacFragment).hide(findFragment).hide(settingFragment).show(mainFragment).commit();
    }

    /**
     * button
     * 
     * @param view
     */
    public void onTabClicked(View view) {
        switch (view.getId()) {
        case R.id.btn_main_invitation:
            index = 0;
            break;
        case R.id.btn_find:
            index = 1;
            break;
        case R.id.btn_address_list:
            index = 2;
            break;
        case R.id.btn_setting:
            index = 3;
            break;
        }
        if (currentTabIndex != index) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[currentTabIndex]);
            if (!fragments[index].isAdded()) {
                trx.add(R.id.fragment_container, fragments[index]);
            }
            trx.show(fragments[index]).commit();
        }
        mTabs[currentTabIndex].setSelected(false);
        // ?tab?
        mTabs[index].setSelected(true);
        currentTabIndex = index;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 
        try {
            unregisterReceiver(msgReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(ackMessageReceiver);
        } catch (Exception e) {
        }
        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }

    }

    /**
     * ?
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
            cacFragment.getUnreadLabel().setText(String.valueOf(count));
            cacFragment.getUnreadLabel().setVisibility(View.VISIBLE);
        } else {
            cacFragment.getUnreadLabel().setVisibility(View.INVISIBLE);
        }
    }

    /**
     * ?
     */
    public void updateUnreadAddressLable() {
        runOnUiThread(new Runnable() {
            public void run() {
                int count = getUnreadAddressCountTotal();
                if (count > 0) {
                    cacFragment.getUnreadAddressLable().setText(String.valueOf(count));
                    cacFragment.getUnreadAddressLable().setVisibility(View.VISIBLE);
                } else {
                    cacFragment.getUnreadAddressLable().setVisibility(View.INVISIBLE);
                }
            }
        });

    }

    /**
     * ??
     * 
     * @return
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;
        if (App.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME) != null)
            unreadAddressCountTotal = App.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME)
                    .getUnreadMsgCount();
        return unreadAddressCountTotal;
    }

    /**
     * ??
     * 
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
        return unreadMsgCountTotal;
    }

    /**
     * ?
     * 
     * 
     */
    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // ????????chat?

            // ?id
            //         String msgId = intent.getStringExtra("msgid");
            // message?db?id?mesage
            // EMMessage message =
            // EMChatManager.getInstance().getMessage(msgId);

            // bottom bar?
            updateUnreadLabel();
            // ??????
            if (cacFragment != null && cacFragment.getChatHistoryFragment() != null
                    && cacFragment.getChatHistoryFragment().isInitialized()) {
                cacFragment.getChatHistoryFragment().refresh();
            }
            // ?ChatActivity
            abortBroadcast();
        }
    }

    /**
     * ?BroadcastReceiver
     */
    private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String msgid = intent.getStringExtra("msgid");
            String from = intent.getStringExtra("from");
            EMConversation conversation = EMChatManager.getInstance().getConversation(from);
            if (conversation != null) {
                // message
                EMMessage msg = conversation.getMessage(msgid);
                if (msg != null) {
                    msg.isAcked = true;
                }
            }
            abortBroadcast();
        }
    };

    /**
     * ?BroadcastReceiver sdk ????clientreceiverUI
     * ??? UI ????
     */
    // private BroadcastReceiver offlineMessageReceiver = new
    // BroadcastReceiver() {
    //
    // @Override
    // public void onReceive(Context context, Intent intent) {
    // String[] users = intent.getStringArrayExtra("fromuser");
    // String[] groups = intent.getStringArrayExtra("fromgroup");
    // if (users != null) {
    // for (String user : users) {
    // System.out.println("user?" + user);
    // }
    // }
    // if (groups != null) {
    // for (String group : groups) {
    // System.out.println("group?" + group);
    // }
    // }
    // abortBroadcast();
    // }
    // };

    private InviteMessgeDao inviteMessgeDao;
    private UserDao userDao;

    /***
     * ??listener
     * 
     */
    private class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(List<String> usernameList) {
            // ??
            //1???
            //2??
            getUserInfoFromBmob(usernameList);
        }

        private void getUserInfoFromBmob(List<String> usernameList) {
            // TODO Auto-generated method stub
            BmobQuery<LXHUser> query = new BmobQuery<LXHUser>();
            query.addWhereContainedIn("objectId", usernameList);
            query.addQueryKeys("objectId,nickName,headUrl");
            query.findObjects(MainActivity.this, new FindListener<LXHUser>() {

                @Override
                public void onSuccess(List<LXHUser> arg0) {
                    // TODO Auto-generated method stub
                    Map<String, User> localUsers = App.getInstance().getContactList();
                    Map<String, User> toAddUsers = new HashMap<String, User>();
                    // Log.i("UserLogin", "??"+usernames.size());
                    for (int i = 0; i < arg0.size(); i++) {
                        User user = new User();
                        String userName = arg0.get(i).getObjectId();
                        user.setUsername(userName);
                        user.setNickName(arg0.get(i).getNickName());
                        user.setHeadUrl(arg0.get(i).getHeadUrl());
                        setUserHead(userName, user);
                        // bug??added
                        if (!localUsers.containsKey(userName)) {
                            userDao.saveContact(user);
                        }
                        toAddUsers.put(userName, user);
                        Log.i("UserLogin", "??" + userName + "---"
                                + arg0.get(i).getNickName() + "---" + arg0.get(i).getHeadUrl());
                    }
                    localUsers.putAll(toAddUsers);
                    // ui
                    if (cacFragment != null && cacFragment.getContactListFragment() != null) {
                        Log.i("MainActivity", "add");
                        cacFragment.getContactListFragment().refresh();
                    }
                }

                @Override
                public void onError(int arg0, String arg1) {
                    // TODO Auto-generated method stub

                }
            });
        }

        @Override
        public void onContactDeleted(final List<String> usernameList) {
            //         // 
            //         Map<String, User> localUsers = App.getInstance().getContactList();
            //         for (String username : usernameList) {
            //            localUsers.remove(username);
            //            userDao.deleteContact(username);
            //            inviteMessgeDao.deleteMessage(username);
            //         }
            //         runOnUiThread(new Runnable() {
            //            public void run() {
            //               // ??
            //               if (ChatActivity.activityInstance != null
            //                     && usernameList
            //                           .contains(ChatActivity.activityInstance
            //                                 .getToChatUsername())) {
            //                  Toast.makeText(
            //                        MainActivity.this,
            //                        ChatActivity.activityInstance
            //                              .getToChatUsername() + "?",
            //                        Toast.LENGTH_SHORT).show();
            //                  ChatActivity.activityInstance.finish();
            //               }
            //               updateUnreadLabel();
            //            }
            //         });
            //         // ui
            //         if (cacFragment != null
            //               && cacFragment.getContactListFragment() != null) {
            //            Log.i("MainActivity", "delete");
            //            cacFragment.getContactListFragment().refresh();
            //         }

        }

        @Override
        public void onContactInvited(String username, String reason) {
            // // ???(???)???????????
            // List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
            // for (InviteMessage inviteMessage : msgs) {
            // if (inviteMessage.getGroupId() == null &&
            // inviteMessage.getFrom().equals(username)) {
            // inviteMessgeDao.deleteMessage(username);
            // }
            // }
            // // ?javabean
            // InviteMessage msg = new InviteMessage();
            // msg.setFrom(username);
            // msg.setTime(System.currentTimeMillis());
            // msg.setReason(reason);
            // Log.d(TAG, username + "?,reason: " + reason);
            // // status
            // msg.setStatus(InviteMesageStatus.BEINVITEED);
            // notifyNewIviteMessage(msg);

        }

        @Override
        public void onContactAgreed(String username) {
            // List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
            // for (InviteMessage inviteMessage : msgs) {
            // if (inviteMessage.getFrom().equals(username)) {
            // return;
            // }
            // }
            // // ?javabean
            // InviteMessage msg = new InviteMessage();
            // msg.setFrom(username);
            // msg.setTime(System.currentTimeMillis());
            // Log.d(TAG, username + "???");
            // msg.setStatus(InviteMesageStatus.BEAGREED);
            // notifyNewIviteMessage(msg);

        }

        @Override
        public void onContactRefused(String username) {
            // ???,demo

        }

    }

    /**
     * ????
     * 
     * @param msg
     */
    private void notifyNewIviteMessage(InviteMessage msg) {
        saveInviteMsg(msg);
        // ???
        EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

        // bottom bar?
        updateUnreadAddressLable();
        // ??ui
        if (cacFragment != null && cacFragment.getContactListFragment() != null) {
            cacFragment.getContactListFragment().refresh();
        }
    }

    /**
     * ?msg
     * 
     * @param msg
     */
    private void saveInviteMsg(InviteMessage msg) {
        // ?msg
        inviteMessgeDao.saveMessage(msg);
        // 1
        User user = App.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME);
        user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
    }

    /**
     * set head
     * 
     * @param username
     * @return
     */
    void setUserHead(String username, User user) {
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNickName())) {
            headerName = user.getNickName();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1)
                    .toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
    }

    /**
     * ?listener
     * 
     */
    private class MyConnectionListener implements ConnectionListener {

        @Override
        public void onConnected() {
            Log.i("MyConnectionListener", "??");
            if (cacFragment != null && cacFragment.getChatHistoryFragment() != null
                    && cacFragment.getChatHistoryFragment().errorItem != null) {
                cacFragment.getChatHistoryFragment().errorItem.setVisibility(View.GONE);
            }
        }

        @Override
        public void onDisConnected(String errorString) {
            Log.i("MyConnectionListener", "" + errorString);
            if (errorString != null && errorString.contains("conflict")) {
                // ??dialog
                showConflictDialog();
            } else {
                if (cacFragment != null && cacFragment.getChatHistoryFragment() != null
                        && cacFragment.getChatHistoryFragment().errorItem != null) {
                    cacFragment.getChatHistoryFragment().errorItem.setVisibility(View.VISIBLE);
                    if (NetUtils.hasNetwork(MainActivity.this)) {
                        cacFragment.getChatHistoryFragment().errorText.setText("???");
                    } else {
                        cacFragment.getChatHistoryFragment().errorText
                                .setText("???");
                    }
                }
            }
        }

        @Override
        public void onReConnected() {
            if (cacFragment != null && cacFragment.getChatHistoryFragment() != null
                    && cacFragment.getChatHistoryFragment().errorItem != null) {
                cacFragment.getChatHistoryFragment().errorItem.setVisibility(View.GONE);
            }
        }

        @Override
        public void onReConnecting() {
        }

        @Override
        public void onConnecting(String progress) {
        }

    }

    /**
     * MyGroupChangeListener
     */
    private class MyGroupChangeListener implements GroupChangeListener {

        @Override
        public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) {
            boolean hasGroup = false;
            for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
                if (group.getGroupId().equals(groupId)) {
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 
            EMMessage msg = EMMessage.createReceiveMessage(Type.TXT);
            msg.setChatType(ChatType.GroupChat);
            msg.setFrom(inviter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(inviter + "?"));
            // ??
            EMChatManager.getInstance().saveMessage(msg);
            // ???
            EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    // ui
                    // ??????
                    if (cacFragment != null && cacFragment.getChatHistoryFragment() != null
                            && cacFragment.getChatHistoryFragment().isInitialized()) {
                        cacFragment.getChatHistoryFragment().refresh();
                    }
                    if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onInvitationAccpted(String groupId, String inviter, String reason) {

        }

        @Override
        public void onInvitationDeclined(String groupId, String invitee, String reason) {

        }

        @Override
        public void onUserRemoved(String groupId, String groupName) {
            // ??Tdemo?
            // ui
            runOnUiThread(new Runnable() {
                public void run() {
                    try {
                        updateUnreadLabel();
                        // ??????
                        if (cacFragment != null && cacFragment.getChatHistoryFragment() != null
                                && cacFragment.getChatHistoryFragment().isInitialized()) {
                            cacFragment.getChatHistoryFragment().refresh();
                        }
                        if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                            GroupsActivity.instance.onResume();
                        }
                    } catch (Exception e) {
                        Log.e("###", "refresh exception " + e.getMessage());
                    }

                }
            });
        }

        @Override
        public void onGroupDestroy(String groupId, String groupName) {
            // 
            // ??,demo?
            // ui
            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    // ??????
                    if (cacFragment != null && cacFragment.getChatHistoryFragment() != null
                            && cacFragment.getChatHistoryFragment().isInitialized()) {
                        cacFragment.getChatHistoryFragment().refresh();
                    }
                    if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onApplicationReceived(String groupId, String groupName, String applyer, String reason) {
            // ?
            InviteMessage msg = new InviteMessage();
            msg.setFrom(applyer);
            msg.setTime(System.currentTimeMillis());
            msg.setGroupId(groupId);
            msg.setGroupName(groupName);
            msg.setReason(reason);
            msg.setStatus(InviteMesageStatus.BEAPPLYED);
            notifyNewIviteMessage(msg);
        }

        @Override
        public void onApplicationAccept(String groupId, String groupName, String accepter) {
            // ??
            EMMessage msg = EMMessage.createReceiveMessage(Type.TXT);
            msg.setChatType(ChatType.GroupChat);
            msg.setFrom(accepter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(accepter + "???"));
            // ????
            EMChatManager.getInstance().saveMessage(msg);
            // ???
            EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    // ui
                    // ??????
                    if (cacFragment != null && cacFragment.getChatHistoryFragment() != null
                            && cacFragment.getChatHistoryFragment().isInitialized()) {
                        cacFragment.getChatHistoryFragment().refresh();
                    }
                    if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });
        }

        @Override
        public void onApplicationDeclined(String groupId, String groupName, String decliner, String reason) {
            // ?demo
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        if (!isConflict && App.isLogin()) {
            updateUnreadLabel();
            updateUnreadAddressLable();
            EMChatManager.getInstance().activityResumed();
            if (currentTabIndex == 2) {
                if (cacFragment != null && cacFragment.getContactListFragment() != null) {
                    Log.i("MainActivity", "add");
                    cacFragment.getContactListFragment().refresh();
                }
            }
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //??
            App.pre.edit().putInt(Global.CURRENT_NATIVE, 0).commit();
            App.pre.edit().putBoolean(Global.IS_MAIN_LIST_NEED_REFRESH, true).commit();
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private android.app.AlertDialog.Builder conflictBuilder;
    private boolean isConflictDialogShow;

    /**
     * ??dialog
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        App.getInstance().logout();

        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)
                    conflictBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
                conflictBuilder.setTitle("");
                conflictBuilder.setMessage(R.string.connect_conflict);
                conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        conflictBuilder = null;
                        finish();
                        startActivity(new Intent(MainActivity.this, WelcomeActivity.class));
                    }
                });
                conflictBuilder.setCancelable(false);
                conflictBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {
                Log.e("###", "---------color conflictBuilder error" + e.getMessage());
            }

        }

    }

    /**
     * ??
     */
    @Override
    public void onResponse(BaseResponse baseResp) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        switch (baseResp.errCode) {
        case WBConstants.ErrorCode.ERR_OK:
            // Toast.makeText(getActivity(),
            // R.string.weibosdk_demo_toast_share_success,
            // Toast.LENGTH_LONG).show();
            break;
        case WBConstants.ErrorCode.ERR_CANCEL:
            // Toast.makeText(getActivity(),
            // R.string.weibosdk_demo_toast_share_canceled,
            // Toast.LENGTH_LONG).show();
            break;
        case WBConstants.ErrorCode.ERR_FAIL:
            // Toast.makeText(
            // getActivity(),
            // getString(R.string.weibosdk_demo_toast_share_failed)
            // + "Error Message: " + baseResp.errMsg,
            // Toast.LENGTH_LONG).show();
            break;
        }
    }

    //   private Dialog loginDialog;
    //
    //   public void showLoginDialog() {
    //      // TODO Auto-generated method stub
    //      loginDialog = new MyLoginDialog(this, R.style.MyDialog);
    //      loginDialog.show();
    //   }

    /**
     *  SSO ? Activity 
     * 
     * @see {@link Activity#onActivityResult}
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // SSO ?
        // ??? SSO  Activity ? onActivityResult
        if (shareWeibo.getmSsoHandler() != null) {
            shareWeibo.getmSsoHandler().authorizeCallBack(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (getIntent().getBooleanExtra("conflict", false) && !isConflictDialogShow) {
            showConflictDialog();
        }
        // ?????
        // ???? true
        // {@link IWeiboHandler.Response#onResponse} false?
        // mWeiboShareAPI.handleWeiboResponse(intent, getActivity());
        shareWeibo.getmWeiboShareAPI().handleWeiboResponse(intent, this);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPause(this);
    }
}