cn.kangeqiu.kq.activity.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for cn.kangeqiu.kq.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 cn.kangeqiu.kq.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

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.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.kangeqiu.kq.Constant;
import cn.kangeqiu.kq.R;
import cn.kangeqiu.kq.db.InviteMessgeDao;
import cn.kangeqiu.kq.db.UserDao;
import cn.kangeqiu.kq.domain.InviteMessage;
import cn.kangeqiu.kq.domain.User;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.EMNotifier;
import com.easemob.util.EMLog;
import com.easemob.util.HanziToPinyin;
import com.jingyi.MiChat.application.BaseApplication;
import com.jingyi.MiChat.core.http.MCHttpCallBack;
import com.jingyi.MiChat.core.http.MCHttpResp;
import com.medicine.app.BaseActivity;
import com.medicine.app.fragments.MenuFragment;
import com.medicine.app.sm.SlidingMenu;
import com.nowagame.kq.activity.MineActivity;
import com.nowagme.football.AppConfig;
import com.nowagme.football.FragmentData;
import com.nowagme.football.FragmentMatch;
import com.nowagme.util.HttpPostUtil;
import com.nowagme.util.MyActivityManager;
import com.nowagme.util.WebRequestUtil;
import com.tendcloud.tenddata.TCAgent;
import com.umeng.analytics.MobclickAgent;

//import com.umeng.analytics.MobclickAgent;

public class MainActivity extends BaseActivity {

    protected static final String TAG = "MainActivity";
    // ?textview
    private TextView unreadLabel;
    // textview
    // private TextView unreadAddressLable;

    private Button[] mTabs;
    private ContactlistFragment contactListFragment;
    // private ChatHistoryFragment chatHistoryFragment;
    private ChatAllHistoryFragment chatHistoryFragment;
    private SettingsFragment settingFragment;
    private MineActivity personFragment;
    private MenuFragment menuFragment;
    private FragmentMatch teamFragment;
    private FragmentData dataFragment;

    // private FragmentNearbyNew nearbyFragment;
    // private FragmentFinder finderFragment;
    private Fragment[] fragments;
    private int index;
    private Context context;
    private boolean progressShow;
    // ?fragmentindex
    private int currentTabIndex;
    private NewMessageBroadcastReceiver msgReceiver;
    // ?
    public boolean isConflict = false;
    // ?
    private boolean isCurrentAccountRemoved = false;
    // public static DrawerLayout mDrawerLayout = null;
    // private RelativeLayout lv = null;
    private long keyDownTime;
    private int count = 0;
    // ?
    LocationClient mLocClient;
    boolean isFirstLoc = true;// ??
    private double lastLatitude = 0.0, lastLongitude = 0.0;// ?

    // private RelativeLayout drawer_1, drawer_2, drawer_3, drawer_4;

    /**
     * ??
     */
    public boolean getCurrentAccountRemoved() {
        return isCurrentAccountRemoved;
    }

    private Fragment mContent;
    FrameLayout frame;
    RelativeLayout containter;

    public MainActivity() {
        super(R.string.app_name);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        getSupportFragmentManager().putFragment(outState, "mContent", mContent);
        outState.putBoolean("isConflict", isConflict);
        outState.putBoolean(Constant.ACCOUNT_REMOVED, isCurrentAccountRemoved);
    }

    public void openMenu() {
        getSlidingMenu().showMenu();
    }

    public void switchContent(Fragment fragment) {
        mContent = fragment;
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
        getSlidingMenu().showContent();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
        case 200:// ?
            if (personFragment.intr == 1) {
                menuFragment.inidate();
                personFragment.initData();
            } else {
                menuFragment.inidate();
            }
            // if (requestCode==0) {
            // personFragment.initData();
            //
            // }else if(requestCode==1){
            //
            // }
            // initData(true);

            break;
        case 300:// ?
            // initData(true);
            finish();
            startActivity(new Intent(context, LoginActivity.class));
            break;
        case RESULT_OK:
            if (requestCode == MineActivity.REQUEST_CODE_FANS) {
                personFragment.initData();
            } else if (requestCode == MineActivity.REQUEST_CODE_GUANZHU) {
                personFragment.initData();
            } else if (requestCode == ChatAllHistoryFragment.REQUEST_CODE_CREATE_HOURSE) {
                chatHistoryFragment.RefreshData();
            }
            break;
        }

    }

    /**
     * ?.
     */
    private void initBaiduLocation() {
        // ??
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                postBaiduLocation(location);
            }

            @Override
            public void onReceivePoi(BDLocation location) {
                postBaiduLocation(location);
            }
        });
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// gps
        option.setCoorType(AppConfig.getInstance().getCoordType()); // ??
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * ??.
     * 
     * @param location
     */
    private void postBaiduLocation(BDLocation location) {
        if (location == null)
            return;
        if (location.getLatitude() == lastLatitude && location.getLongitude() == lastLongitude)
            return;

        // ?
        lastLatitude = location.getLatitude();
        lastLongitude = location.getLongitude();

        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("app_action", "1002");
        parameters.put("app_platform", "0");
        parameters.put("u_uid", String.valueOf(AppConfig.getInstance().getPlayerId()));
        parameters.put("u_w", String.valueOf(location.getLatitude()));
        parameters.put("u_j", String.valueOf(location.getLongitude()));

        HttpPostUtil mHttpPostUtil = null;
        try {
            AppConfig.getInstance().addSign(parameters);
            mHttpPostUtil = AppConfig.getInstance().makeHttpPostUtil(parameters);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // WEB request and deal the listener
        // new WebRequestUtil(mHttpPostUtil).execute(new
        // WebRequestUtilListener() {
        //
        // @Override
        // public void onSucces(Map<String, Object> data) {
        // Log.d(TAG, "success");
        // }
        //
        // @Override
        // public void onFail(Map<String, Object> data) {
        // Log.v(TAG, "faild:" + data.get("message"));
        // }
        //
        // @Override
        // public void onError() {
        // Log.v(TAG, "post error");
        // }
        // });

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null)
            mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
        if (mContent == null)
            mContent = new FragmentMatch(R.color.red);
        // set the Above View
        setContentView(R.layout.content_frame);
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit();
        // set the Behind View
        setBehindContentView(R.layout.menu_frame);
        menuFragment = new MenuFragment();
        personFragment = new MineActivity();
        getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame, menuFragment).commit();
        // customize the SlidingMenu
        getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        context = this;
        if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) {
            // ??home???appcrash
            // fragment??
            BaseApplication.getInstance().logout(null);
            finish();
            startActivity(new Intent(this, LoginActivity.class));
            return;
        } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
            // T??home???appcrash
            // fragment??
            finish();
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        setContentView(R.layout.activity_main);
        initView();

        // MobclickAgent.setDebugMode( true );
        // --?--
        // MobclickAgent.updateOnlineConfig(this);

        if (getIntent().getBooleanExtra("conflict", false) && !isConflictDialogShow) {
            showConflictDialog();
        } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
            showAccountRemovedDialog();
        }

        inviteMessgeDao = new InviteMessgeDao(this);
        userDao = new UserDao(this);
        // fragment???
        // chatHistoryFragment = new ChatHistoryFragment();
        // ?fragment
        chatHistoryFragment = new ChatAllHistoryFragment();
        // contactListFragment = new ContactlistFragment();
        // settingFragment = new SettingsFragment();
        teamFragment = new FragmentMatch();
        dataFragment = new FragmentData();
        // nearbyFragment = new FragmentNearbyNew();
        // finderFragment = new FragmentFinder();
        // fragments = new Fragment[] { chatHistoryFragment,
        // nearbyFragment,finderFragment, teamFragment, personFragment };
        fragments = new Fragment[] { teamFragment, chatHistoryFragment, dataFragment, personFragment };
        // fragment
        // getSupportFragmentManager().beginTransaction()
        // .add(R.id.fragment_container, teamFragment).show(teamFragment)
        // .commit();

        // getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,
        // chatHistoryFragment)
        // .add(R.id.fragment_container,
        // contactListFragment).hide(contactListFragment).show(chatHistoryFragment).commit();

        // ?BroadcastReceiver
        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 cmdMessageIntentFilter = new IntentFilter(
                EMChatManager.getInstance().getCmdMessageBroadcastAction());
        cmdMessageIntentFilter.setPriority(3);
        registerReceiver(cmdMessageReceiver, cmdMessageIntentFilter);

        // ?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();

        // ??
        // initBaiduLocation();
    }

    public void refreshMatch() {
        teamFragment.refreshMatch();
    }

    public void refreshMessage(int hourseNum) {
        chatHistoryFragment.refreshMessage(hourseNum, count - hourseNum);
    }

    /**
     * ?
     */
    private void initView() {
        frame = (FrameLayout) findViewById(R.id.content_frame);
        unreadLabel = (TextView) findViewById(R.id.unread_msg_number);
        containter = (RelativeLayout) findViewById(R.id.fragment_container);
        mTabs = new Button[4];
        mTabs[0] = (Button) findViewById(R.id.btn_team);
        mTabs[1] = (Button) findViewById(R.id.btn_conversation);
        mTabs[2] = (Button) findViewById(R.id.btn_data);
        mTabs[3] = (Button) findViewById(R.id.btn_person);
        // tab?
        mTabs[0].setSelected(true);
    }

    /**
     * button
     * 
     * @param view
     */
    public void onTabClicked(View view) {
        switch (view.getId()) {
        case R.id.btn_team:
            index = 0;
            MobclickAgent.onEvent(this, "match_live");
            TCAgent.onEvent(this, "match_live");

            break;
        case R.id.btn_conversation:
            index = 1;
            break;
        case R.id.btn_data:
            index = 2;
            MobclickAgent.onEvent(this, "data");
            TCAgent.onEvent(this, "data");

            break;
        case R.id.btn_person:
            index = 3;

            personFragment.initData();
            break;
        }

        if (currentTabIndex != index) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[currentTabIndex]);
            if (!fragments[index].isAdded()) {
                frame.setVisibility(View.GONE);
                containter.setVisibility(View.VISIBLE);
                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();

        // ??
        if (mLocClient != null)
            mLocClient.stop();

        // 
        try {
            unregisterReceiver(msgReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(ackMessageReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(cmdMessageReceiver);
        } catch (Exception e) {
        }

        // try {
        // unregisterReceiver(offlineMessageReceiver);
        // } catch (Exception e) {
        // }

        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }

    }

    /**
     * ?????.
     */
    public void updateUnreadLabel() {
        ArrayList<NameValuePair> pair = new ArrayList<NameValuePair>();
        pair.add(new BasicNameValuePair("app_action", "2025"));
        pair.add(new BasicNameValuePair("app_platform", "0"));
        pair.add(new BasicNameValuePair("u_uid", AppConfig.getInstance().getPlayerId() + ""));
        new WebRequestUtil().execute(true, AppConfig.getInstance().makeUrl(Integer.parseInt("2025")), pair,
                new MCHttpCallBack() {
                    @Override
                    public void onSuccess(MCHttpResp resp) {
                        super.onSuccess(resp);
                        try {

                            String resultCode = resp.getJson().getString("result_code");
                            if (resultCode.equals("0")) {
                                JSONArray records = (JSONArray) resp.getJson().getJSONArray("records");
                                int counts = 0;
                                for (int i = 0; i < records.length(); i++) {
                                    // ?
                                    String unread_count = records.getJSONObject(i).getString("unread_count");
                                    if (unread_count == null || unread_count.length() == 0)
                                        unread_count = "0";
                                    int count = Integer.parseInt(unread_count);
                                    counts += count;
                                }
                                updateAllUnreadLabel(counts);
                            } else {
                                Toast.makeText(context, resp.getJson().getString("message"), Toast.LENGTH_SHORT)
                                        .show();
                            }

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

                    @Override
                    public void onError(MCHttpResp resp) {
                        super.onError(resp);
                        Toast.makeText(MainActivity.this, resp.getErrorMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

    }

    /**
     * ?
     */
    public void updateAllUnreadLabel(int sysUnreadCount) {
        // ???
        int countNormal = getUnreadMsgCountTotal();

        // ?
        count = countNormal + sysUnreadCount;

        // update
        if (count > 0) {
            unreadLabel.setText(String.valueOf(count));
            unreadLabel.setVisibility(View.VISIBLE);
        } else {
            unreadLabel.setVisibility(View.INVISIBLE);
        }
    }

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

    }

    /**
     * ??
     * 
     * @return
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;
        if (BaseApplication.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME) != null)
            unreadAddressCountTotal = BaseApplication.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?

            String from = intent.getStringExtra("from");
            // ?id
            String msgId = intent.getStringExtra("msgid");
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);
            // 2014-10-22 ?????????bug
            if (ChatActivity.activityInstance != null) {
                if (message.getChatType() == ChatType.GroupChat) {
                    if (message.getTo().equals(ChatActivity.activityInstance.getToChatUsername()))
                        return;
                } else {
                    if (from.equals(ChatActivity.activityInstance.getToChatUsername()))
                        return;
                }
            }

            // ?ChatActivity
            abortBroadcast();

            notifyNewMessage(message);

            // bottom bar?
            updateUnreadLabel();
            if (currentTabIndex == 1) {
                // ??????
                if (chatHistoryFragment != null) {
                    chatHistoryFragment.refresh();
                }
            }

        }
    }

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

        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();

            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) {

                    // 2014-11-5 ????????bug
                    if (ChatActivity.activityInstance != null) {
                        if (msg.getChatType() == ChatType.Chat) {
                            if (from.equals(ChatActivity.activityInstance.getToChatUsername()))
                                return;
                        }
                    }

                    msg.isAcked = true;
                }
            }

        }
    };

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

        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();
            EMLog.d(TAG, "??");
            // ?cmd message
            @SuppressWarnings("unused")
            String msgId = intent.getStringExtra("msgid");
            EMMessage message = intent.getParcelableExtra("message");
            // ??body
            CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
            String action = cmdMsgBody.action;// ?action

            // ? ?
            // message.getStringAttribute("");
            EMLog.d(TAG, String.format("??action:%s,message:%s", action, message.toString()));
            String st9 = getResources().getString(R.string.receive_the_passthrough);
            // Toast.makeText(MainActivity.this, st9 + action,
            // Toast.LENGTH_SHORT)
            // .show();

            // 
            updateUnreadLabel();

            if (currentTabIndex == 1) {
                // ??????
                if (chatHistoryFragment != null) {
                    chatHistoryFragment.refresh();
                }
            }
        }
    };

    /**
     * ?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);
    // }
    // }
    // }
    // };

    private InviteMessgeDao inviteMessgeDao;
    private UserDao userDao;

    /***
     * ??listener
     * 
     */
    // private class MyContactListener implements EMContactListener {
    //
    // @Override
    // public void onContactAdded(List<String> usernameList) {
    // // ??
    // Map<String, User> localUsers = BaseApplication.getInstance()
    // .getContactList();
    // Map<String, User> toAddUsers = new HashMap<String, User>();
    // for (String username : usernameList) {
    // User user = setUserHead(username);
    // // ??added
    // if (!localUsers.containsKey(username)) {
    // userDao.saveContact(user);
    // }
    // toAddUsers.put(username, user);
    // }
    // localUsers.putAll(toAddUsers);
    // // ui
    // if (currentTabIndex == 1)
    // contactListFragment.refresh();
    //
    // }
    //
    // @Override
    // public void onContactDeleted(final List<String> usernameList) {
    // // 
    // Map<String, User> localUsers = BaseApplication.getInstance()
    // .getContactList();
    // for (String username : usernameList) {
    // localUsers.remove(username);
    // userDao.deleteContact(username);
    // inviteMessgeDao.deleteMessage(username);
    // }
    // runOnUiThread(new Runnable() {
    // public void run() {
    // // ??
    // String st10 = getResources().getString(
    // R.string.have_you_removed);
    // if (ChatActivity.activityInstance != null
    // && usernameList
    // .contains(ChatActivity.activityInstance
    // .getToChatUsername())) {
    // Toast.makeText(
    // MainActivity.this,
    // ChatActivity.activityInstance
    // .getToChatUsername() + st10,
    // Toast.LENGTH_LONG).show();
    // ChatActivity.activityInstance.finish();
    // }
    // updateUnreadLabel();
    // // ui
    // if (currentTabIndex == 1)
    // contactListFragment.refresh();
    // else if (currentTabIndex == 0)
    // chatHistoryFragment.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
    // Log.d(username, username + "??");
    // }
    //
    // }

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

        // bottom bar?
        updateUnreadAddressLable();
        // ??ui
        // if (currentTabIndex == 1)
        // contactListFragment.refresh();
    }

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

    /**
     * set head
     * 
     * @param username
     * @return
     */
    User setUserHead(String username) {
        User user = new User();
        user.setUsername(username);
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } 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("#");
            }
        }
        return user;
    }

    /**
     * ?listener
     * 
     */
    // private class MyConnectionListener implements EMConnectionListener {
    //
    // @Override
    // public void onConnected() {
    // runOnUiThread(new Runnable() {
    //
    // @Override
    // public void run() {
    // chatHistoryFragment.errorItem.setVisibility(View.GONE);
    // }
    //
    // });
    // }
    //
    // @Override
    // public void onDisconnected(final int error) {
    // final String st1 = getResources().getString(
    // R.string.Less_than_chat_server_connection);
    // final String st2 = getResources().getString(
    // R.string.the_current_network);
    // runOnUiThread(new Runnable() {
    //
    // @Override
    // public void run() {
    // if (error == EMError.USER_REMOVED) {
    // // ???
    // showAccountRemovedDialog();
    // } else if (error == EMError.CONNECTION_CONFLICT) {
    // // ??dialog
    // showConflictDialog();
    // } else {
    // chatHistoryFragment.errorItem
    // .setVisibility(View.VISIBLE);
    // if (NetUtils.hasNetwork(MainActivity.this))
    // chatHistoryFragment.errorText.setText(st1);
    // else
    // chatHistoryFragment.errorText.setText(st2);
    //
    // }
    // }
    //
    // });
    // }
    // }

    /**
     * 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;
    //
    // // 
    // String st3 = getResources().getString(
    // R.string.Invite_you_to_join_a_group_chat);
    // 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 + st3));
    // // ??
    // EMChatManager.getInstance().saveMessage(msg);
    // // ???
    // EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();
    //
    // runOnUiThread(new Runnable() {
    // public void run() {
    // updateUnreadLabel();
    // // ui
    // if (currentTabIndex == 0)
    // chatHistoryFragment.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 (currentTabIndex == 0)
    // chatHistoryFragment.refresh();
    // if (CommonUtils.getTopActivity(MainActivity.this)
    // .equals(GroupsActivity.class.getName())) {
    // GroupsActivity.instance.onResume();
    // }
    // } catch (Exception e) {
    // EMLog.v(TAG, "refresh exception " + e.getMessage());
    // }
    // }
    // });
    // }
    //
    // @Override
    // public void onGroupDestroy(String groupId, String groupName) {
    // // 
    // // ??,demo?
    // // ui
    // runOnUiThread(new Runnable() {
    // public void run() {
    // updateUnreadLabel();
    // if (currentTabIndex == 0)
    // chatHistoryFragment.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);
    // Log.d(TAG, applyer + " ?" + groupName);
    // msg.setStatus(InviteMesageStatus.BEAPPLYED);
    // notifyNewIviteMessage(msg);
    // }
    //
    // @Override
    // public void onApplicationAccept(String groupId, String groupName,
    // String accepter) {
    // String st4 = getResources().getString(
    // R.string.Agreed_to_your_group_chat_application);
    // // ??
    // 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 + st4));
    // // ????
    // EMChatManager.getInstance().saveMessage(msg);
    // // ???
    // EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();
    //
    // runOnUiThread(new Runnable() {
    // public void run() {
    // updateUnreadLabel();
    // // ui
    // if (currentTabIndex == 0)
    // chatHistoryFragment.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();
        if (!isConflict || !isCurrentAccountRemoved) {
            updateUnreadLabel();
            updateUnreadAddressLable();
            EMChatManager.getInstance().activityResumed();
        }

    }

    // @Override
    // protected void onSaveInstanceState(Bundle outState) {
    // outState.putBoolean("isConflict", isConflict);
    // outState.putBoolean(Constant.ACCOUNT_REMOVED, isCurrentAccountRemoved);
    // super.onSaveInstanceState(outState);
    // }

    // @Override
    // public boolean onKeyDown(int keyCode, KeyEvent event) {
    // if (keyCode == KeyEvent.KEYCODE_BACK) {
    // moveTaskToBack(false);
    // return true;
    // }
    // return super.onKeyDown(keyCode, event);
    // }
    private android.app.AlertDialog.Builder conflictBuilder;
    private android.app.AlertDialog.Builder accountRemovedBuilder;
    private boolean isConflictDialogShow;
    private boolean isAccountRemovedDialogShow;

    /**
     * ??dialog
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        BaseApplication.getInstance().logout(null);
        String st = getResources().getString(R.string.Logoff_notification);
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)
                    conflictBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
                conflictBuilder.setTitle(st);
                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, LoginActivity.class));
                    }
                });
                conflictBuilder.setCancelable(false);
                conflictBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {
                EMLog.v(TAG, "---------color conflictBuilder error" + e.getMessage());
            }

        }

    }

    /**
     * ??dialog
     */
    private void showAccountRemovedDialog() {
        isAccountRemovedDialogShow = true;
        BaseApplication.getInstance().logout(null);
        String st5 = getResources().getString(R.string.Remove_the_notification);
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (accountRemovedBuilder == null)
                    accountRemovedBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
                accountRemovedBuilder.setTitle(st5);
                accountRemovedBuilder.setMessage(R.string.em_user_remove);
                accountRemovedBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        accountRemovedBuilder = null;
                        finish();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    }
                });
                accountRemovedBuilder.setCancelable(false);
                accountRemovedBuilder.create().show();
                isCurrentAccountRemoved = true;
            } catch (Exception e) {
                EMLog.v(TAG, "---------color userRemovedBuilder error" + e.getMessage());
            }

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (getIntent().getBooleanExtra("conflict", false) && !isConflictDialogShow) {
            showConflictDialog();
        } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
            showAccountRemovedDialog();
        }
    }

    MyActivityManager mam = MyActivityManager.getInstance();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.v("TAG", "on back1");
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - keyDownTime < 4000) {

                Log.v("tag", "1=" + keyDownTime);
                moveTaskToBack(false);
                mam.finishAllActivity();
                finish();
                return true;
            }

            keyDownTime = System.currentTimeMillis();
            Log.v("tag", "2=" + keyDownTime);
            Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
        }

        return true;
    }
}