xj.property.activity.HXBaseActivity.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for xj.property.activity.HXBaseActivity.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 xj.property.activity.HXBaseActivity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activeandroid.query.Select;
import com.easemob.EMCallBack;
import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatDB;
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.EMNotifier;
import com.easemob.chat.GroupChangeListener;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.EMLog;
import com.easemob.util.HanziToPinyin;
import com.igexin.sdk.PushManager;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.QueryMap;
import xj.property.Constant;
import xj.property.HXSDKHelper;
import xj.property.R;
import xj.property.XjApplication;
import xj.property.activity.tags.MyCommunityCategoryDialog;
import xj.property.beans.AppLoginInfoBean;
import xj.property.beans.CommunityCategoryDataRespBean;
import xj.property.beans.GroupMsgInfoBean;
import xj.property.beans.UpDateApp;
import xj.property.beans.UserInfoDetailBean;
import xj.property.beans.XJUserInfoBean;
import xj.property.cache.GroupHeader;
import xj.property.cache.XJNotify;
import xj.property.db.InviteMessgeDao;
import xj.property.domain.InviteMessage;
import xj.property.domain.InviteMessage.InviteMesageStatus;
import xj.property.domain.User;
import xj.property.event.NewNotifyEvent;
import xj.property.event.NewRefreshIndexMenuEvent;
import xj.property.fragment.ChatAllHistoryFragment;
import xj.property.fragment.IndexFragment;
import xj.property.fragment.MeFragment;
import xj.property.fragment.NewSurroundingFrg;
import xj.property.fragment.SettingsFragment;
import xj.property.netbase.CommonRespBean;
import xj.property.netbase.NetBaseUtils;
import xj.property.netbase.RetrofitFactory;
import xj.property.provider.ChatAllHistoryFProvider;
import xj.property.service.PushPullReqService;
import xj.property.statistic.StatisticAsyncService;
import xj.property.ums.UpdateManager;
import xj.property.utils.CommonUtils;
import xj.property.utils.XJPushManager;
import xj.property.utils.image.utils.StrUtils;
import xj.property.utils.message.XJContactHelper;
import xj.property.utils.message.XJMessageHelper;
import xj.property.utils.other.Config;
import xj.property.utils.other.GroupUtils;
import xj.property.utils.other.PreferencesUtil;
import xj.property.utils.other.UserUtils;

public class MainActivity extends HXBaseActivity implements EMEventListener {
    /**
     * logger
     */

    protected static final String TAG = "MainActivity";
    /// ?
    private static final long DIALOG_SHOW_TIME = 8 * 1000 + 1250;
    /**
     * unread label
     */
    private TextView unreadLabel;
    private TextView tv_newbangbi;

    public static String startTime;
    public static String endTime;
    /**
     * unread address label
     */
    private TextView unreadAddressLabel;
    /**
     * button for tabs
     */
    private Button[] mTabs;
    /**
     * contactListFragment
     */
    //    private ContactlistFragment contactListFragment;
    /**
     * chat history fragment
     */
    public ChatAllHistoryFragment chatHistoryFragment;
    /**
     * setting fragment
     */
    private SettingsFragment settingFragment;
    /**
     * index fragment
     */
    private IndexFragment indexFragment;

    //    private SurroundingsFragment surroundingsFragment;
    //    private PeripheryFragment peripheryFragment;

    private NewSurroundingFrg newSurroundingFrg;

    /**
     * me fragment
     */
    private MeFragment meFragment;// 
    /**
     * array for fragment
     */
    private Fragment[] fragments;
    // private List<Fragment> fragments;

    public static int index;

    private RelativeLayout[] tab_containers;

    private TextView tv_notifycount;

    /**
     * tab index
     */
    private int currentTabIndex;

    //private NewMessageBroadcastReceiver msgReceiver;
    /**
     * login other where
     */
    public boolean isConflict = false;
    private boolean isNetwork = false;
    private boolean isVersionUpdate = false;

    public boolean isX5WebViewEnabled = false;

    /**
     * view pager
     */
    private ViewPager viewPager;

    private String username;
    private String password;

    private String groupId;

    private ChatAllHistoryFProvider mChatAllHistoryFProvider;
    private UserInfoDetailBean userInfoBean;

    /**
     * viewpager adapter
     */
    class PagerAdapter extends FragmentPagerAdapter {
        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return fragments.length;
        }

        @Override
        public Fragment getItem(int arg0) {
            return fragments[arg0];
        }
    }

    public void onEvent(NewRefreshIndexMenuEvent event) {
        if (event != null) {
            Log.d(TAG + " onEvent", "NewRefreshIndexMenuEvent is not null  ");
            int refreshCode = event.refreshCode;
            if (handler != null) {
                //                if(indexFragment!=null){
                //                    indexFragment.getLifeCircleCount(handler);
                //                    Log.d(TAG+" onEvent","NewRefreshIndexMenuEvent  indexFragment getLifeCircleCount ");
                //
                //                    indexFragment.refreshIndexMenu();
                //                    Log.d(TAG+" onEvent","NewRefreshIndexMenuEvent  indexFragment refreshIndexMenu ");
                //
                //                }else{
                //                    Log.d(TAG+" onEvent","NewRefreshIndexMenuEvent  indexFragment is null ");
                //                }
            } else {
                Log.d(TAG + " onEvent", "NewRefreshIndexMenuEvent handler  is null ");
            }
        } else {
            Log.d(TAG + " onEvent", "NewRefreshIndexMenuEvent is null ");
        }
    }

    /**
     * ?
     */
    @Override
    public void onEvent(EMNotifierEvent event) {
        switch (event.getEvent()) {
        case EventNewMessage: // ?
        {
            EMMessage message = (EMMessage) event.getData();
            String from = message.getFrom();
            Log.i("onion", "mainActivity?" + message.getFrom());
            // ?id
            //                if (offlineUser.contains(from)) {
            //                    XJMessageHelper.loadOffLineMessage(EMChatManager.getInstance().getConversation(from));
            //                    offlineUser.remove(from);
            //                    Log.i("onion", "?");
            //                } else
            if (XJMessageHelper.getOrderModel(message.getStringAttribute(Config.EXPKey_serial, ""), 201) != null
                    || XJMessageHelper.getOrderModel(message.getStringAttribute("welfareId", ""), 601) != null
                    || XJMessageHelper.getOrderModel(message.getStringAttribute("welfareId", ""), 602) != null) {
                Log.i("debbug", "?message");
                EMConversation conversation = EMChatManager.getInstance().getConversation(message.getFrom());
                conversation.removeMessage(message.getMsgId());
                EMChatDB.getInstance().deleteMessage(message.getMsgId());
                return;
            }
            if (!XJMessageHelper.operatNewMessage(getmContext(), message)) {
                Log.i("onion", "Main??" + message + message.isUnread());
                XJContactHelper.saveContact(message);
            } else {
                Log.i("onion", "");
                refreshUI();
                refreshNewBangBiUI();
                updateUnreadLabel();
                return;
            }
            if (message.getChatType() == ChatType.GroupChat) {
                GroupHeader header = new Select().from(GroupHeader.class).where("group_id = ?", message.getTo())
                        .executeSingle();
                if (header == null || header.getNum() < 10)
                    GroupUtils.getGroupInfo(message.getTo());
            }

            // 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;
                }
            }
            //
            //todo ?
            // bottom bar?
            // ???
            if (message.getChatType() == ChatType.Chat
                    || !PreferencesUtil.getUnNotifyGroupS(XjApplication.getInstance()).contains(message.getTo()))
                HXSDKHelper.getInstance().getNotifier().onNewMsg(message);
            //TODO refreshUI
            groupId = message.getTo();
            refreshUI(groupId);
            break;
        }

        case EventOfflineMessage: {
            List<EMMessage> offlineMessages = (List<EMMessage>) event.getData();
            Log.i("onion", "offlineMEssage" + offlineMessages.toString());
            XJMessageHelper.loadOffLineMessages(getmContext(), offlineMessages);
            refreshUI();
            break;
        }
        case EventDeliveryAck: {
            EMMessage message = (EMMessage) event.getData();
            Log.i("onion", "??:" + message.getIntAttribute(Config.EXPKey_CMD_CODE, 0)
                    + message.getStringAttribute(Config.EXPKey_serial, "") + message.getBody());
            //    if(message.getIntAttribute(Config.EXPKey_CMD_CODE,0)!=0&&!message.getStringAttribute(Config.EXPKey_serial,"").isEmpty()){
            //        XJMessageHelper.saveMessage2DB(message.getMsgId(),message.getStringAttribute(Config.EXPKey_serial,""),message.getIntAttribute(Config.EXPKey_CMD_CODE,0));
            //    }
            break;
        }
        case EventConversationListChanged: {
            refreshUI();
            break;
        }

        default:
            break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        EMChatManager.getInstance().unregisterEventListener(this);
        HXSDKHelper sdkHelper = (HXSDKHelper) HXSDKHelper.getInstance();
        sdkHelper.popActivity(this);

        //        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    private int selectNewNotifyCount() {
        return new Select().from(XJNotify.class).where("emobid = ? and read_status = ?",
                PreferencesUtil.getLogin(this) ? PreferencesUtil.getLoginInfo(this).getEmobId() : "-1", "no")
                .execute().size();
    }

    //?
    private XJNotify selectNewNotify() {
        return new Select().from(XJNotify.class).orderBy("timestamp DESC").executeSingle();
    }

    // This method will be called when a MessageEvent is posted
    public void onEvent(NewNotifyEvent event) {
        initNotifyCount();
    }

    private void initNotifyCount() {
        int count = selectNewNotifyCount();
        if (count != 0)//
        {
            tv_notifycount.setVisibility(View.VISIBLE);
            tv_notifycount.setText("" + count);
        } else {
            tv_notifycount.setVisibility(View.GONE);
        }
    }

    /**
     * onCreate
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
            // T??home???appcrash
            // fragment??
            finish();
            // startActivity(new Intent(this, LoginActivity.class));
            startActivity(new Intent(this, LoginDialogActivity.class));
            return;
        }
        setContentView(R.layout.activity_main);
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(myNetReceiver, mFilter);
        initView();
        //        MobclickAgent.setDebugMode(true);
        //        MobclickAgent.updateOnlineConfig(this);
        //        EMChatManager.getInstance().getChatOptions().setShowNotificationInBackgroud(false);
        if (getIntent().getBooleanExtra("conflict", false) && !isConflictDialogShow)
            showConflictDialog();

        inviteMessgeDao = new InviteMessgeDao(this);
        //  userDao = new UserDao(this);

        // fragment???
        // chatHistoryFragment = new ChatHistoryFragment();
        // ?fragment
        chatHistoryFragment = new ChatAllHistoryFragment();
        //        contactListFragment = new ContactlistFragment();
        settingFragment = new SettingsFragment();
        indexFragment = new IndexFragment();
        mChatAllHistoryFProvider = new ChatAllHistoryFProvider(getApplicationContext());
        //        surroundingsFragment = new SurroundingsFragment();
        //        peripheryFragment = new PeripheryFragment();
        newSurroundingFrg = new NewSurroundingFrg();

        meFragment = new MeFragment();

        //        fragments = new Fragment[]{indexFragment, chatHistoryFragment,
        //                surroundingsFragment, meFragment};

        fragments = new Fragment[] { indexFragment, chatHistoryFragment, newSurroundingFrg, meFragment };

        tv_notifycount = (TextView) findViewById(R.id.tv_newnotify_count);

        // ?
        viewPager = (ViewPager) findViewById(R.id.vp_index);
        viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
        viewPager.setOffscreenPageLimit(3);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                mTabs[currentTabIndex].setSelected(false);
                // ?tab?
                mTabs[arg0].setSelected(true);
                currentTabIndex = arg0;

                switch (arg0) {
                case 0:
                    indexFragment.getLifeCircleCount(handler);
                    break;
                case 2:
                    Log.i("debbug", "0");
                    PreferencesUtil.saveCrazySalesCount(MainActivity.this, 0);
                    unreadAddressLabel.setVisibility(View.INVISIBLE);

                    //                        indexFragment.eventService("" + 18, "");

                    newSurroundingFrg.updateUI();
                    //                        peripheryFragment.updateUI();

                case 3:
                    Log.i("meFragement tags ", "");
                    PreferencesUtil.saveIsUnReadTagsChange(MainActivity.this, false);
                    break;
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });

        /* IntentFilter offlineMessageIntentFilter = new
            IntentFilter(EMChatManager.getInstance()
            .getOfflineMessageBroadcastAction());
         offlineMessageIntentFilter.setPriority(6);
         registerReceiver(offlineMessageReceiver, offlineMessageIntentFilter);
         // ?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

        //EMChatManager.getInstance().getChatOptions().setNotifyText(new OnMessageNotifyListener() {
        //    @Override
        //    public String onNewMessageNotify(EMMessage message) {
        //        operatNewMessage(message);
        //        return message.getBody().toString();
        //    }
        //
        //    @Override
        //    public String onLatestMessageNotify(EMMessage message, int i, int i2) {
        //        return null;
        //    }
        //
        //    @Override
        //    public String onSetNotificationTitle(EMMessage message) {
        //        return message.getStringAttribute(Config.EXPKey_nickname,"");
        //    }
        //
        //    @Override
        //    public int onSetSmallIcon(EMMessage message) {
        //        return R.drawable.me_arrow;
        //    }
        //});
        // setContactListener???
        EMContactManager.getInstance().setContactListener(new MyContactListener());
        // ??listener
        EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
        // ?listener
        EMGroupManager.getInstance().addGroupChangeListener(new MyGroupChangeListener());

        // sdkUI ??receiverlistener, ??broadcast
        EMChat.getInstance().setAppInited();

        AppLoginInfoBean.Info info = (AppLoginInfoBean.Info) getIntent()
                .getSerializableExtra(Config.IsLoginOtherApp);
        if (null != info) {
            showLogoutDialog("" + StrUtils.getTime4Millions(info.getLoginTime() * 1000L) + "\nid:"
                    + info.getEquipment());
        }

        checkPushUpdate();

        //        UpdateUtils.initUpdate(getmContext());

        //        getRecords(getContentResolver());

        //// 2015/11/11 
        //        if(TimeUtils.isNeedShowRPTopList(this)){
        //            startActivity(new Intent(this, LastWeekRPValueTopListActivity.class));
        //        }

        ////
        //        handler.postDelayed(checkAppUpdate, new Random().nextInt(5) * 1000);
        initUpdate();

        //// ? , ,  , 
        //        PreferencesUtil.setFirstOpen(getmContext(), true);
        if (PreferencesUtil.isFirstOpen(getmContext())) {
            fetchCommunityCategoryData();
        }
        //// ???  2016/1/6
        if (PreferencesUtil.getLogin(this)) {
            long communityId = PreferencesUtil.getLoginInfo(this).getCommunityId();
            String emobId = PreferencesUtil.getLoginInfo(this).getEmobId();
            getGroupMsgsCall((int) communityId, emobId);
        }
        /// X5WebCore
        //        if(!isX5WebViewEnabled){
        //            preinitX5WebCore();
        //        }

    }

    /**
     * X5preinit??
     * X5webviewpreinit???webview?
     * ??X5?X5?????
     */
    private void preinitX5WebCore() {
        if (!QbSdk.isTbsCoreInited()) {// preinit?????view
            QbSdk.preInit(MainActivity.this, myCallback);// X5???
            // ?true?
        }
    }

    private QbSdk.PreInitCallback myCallback = new QbSdk.PreInitCallback() {

        @Override
        public void onViewInitFinished() {// X5webview ???
            new WebView(MainActivity.this);
            MainActivity.this.isX5WebViewEnabled = true;
        }

        @Override
        public void onCoreInitFinished() {
        }
    };

    private void checkPushUpdate() {
        String emobid = PreferencesUtil.getLogin(this) ? PreferencesUtil.getLoginInfo(this).getEmobId()
                : PreferencesUtil.getTourist(this);

        if (xjpushManager != null) {
            xjpushManager.registerPushService(emobid);
        } else {
            xjpushManager = new XJPushManager(this);
            xjpushManager.registerPushService(emobid);
        }
    }

    private android.app.AlertDialog otherAppLogin;

    public void showLogoutDialog(String content) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        View view = View.inflate(this, R.layout.otherapplogin, null);
        final TextView cancle = (TextView) view.findViewById(R.id.cancle);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                otherAppLogin.dismiss();
            }
        });
        ((TextView) view.findViewById(R.id.tv_content)).setText(content);
        otherAppLogin = builder.create();
        otherAppLogin.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        otherAppLogin.setView(view);
        otherAppLogin.setCanceledOnTouchOutside(true);
        otherAppLogin.show();

    }

    ////  oncreate 
    public void initUpdate() {

        String emobId = null;
        int communityId;
        if (PreferencesUtil.getLogin(this)) {
            emobId = PreferencesUtil.getLoginInfo(this).getEmobId();
            communityId = PreferencesUtil.getLoginInfo(this).getCommunityId();
        } else {
            communityId = PreferencesUtil.getCommityId(this);
            if (PreferencesUtil.getTouristLogin(this)) {
                emobId = PreferencesUtil.getTourist(this);
            } else {
                emobId = PreferencesUtil.getlogoutEmobId(this);
            }
        }
        Log.d("checkAppUpdate", "checkAppUpdate  is running ...  ");
        NetBaseUtils.getAppUpdateInfoV3(getmContext(), communityId, emobId,
                new NetBaseUtils.NetRespListener<CommonRespBean<UpDateApp.Info>>() {
                    @Override
                    public void successYes(CommonRespBean<UpDateApp.Info> commonRespBean, Response response) {
                        PreferencesUtil.saveCheckTime(getmContext(), new Date().getTime());
                        String version = "";
                        try {
                            version = UserUtils.getVersion(getmContext());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (equalsVersion(commonRespBean.getData().getVersion(), version)) {
                            tv_newbangbi.setVisibility(View.VISIBLE);
                            Log.d("isVersionUpdate", "isVersionUpdate  VISIBLE ");
                            new UpdateManager(MainActivity.this, commonRespBean.getData().version, "false",
                                    commonRespBean.getData().url, commonRespBean.getData().detail);
                            //                    new UpdateManager(MainActivity.this, Object.getInfo().version, "false", "http://7d9lcl.com2.z0.glb.qiniucdn.com/bangbang_c.apk", Object.getInfo().detail);
                            UpdateManager.showNoticeDialog(MainActivity.this);
                            isVersionUpdate = true;
                        } else {
                            ///   ,? 
                            updateBangZhuNews();
                        }
                    }

                    @Override
                    public void successNo(CommonRespBean<UpDateApp.Info> commonRespBean, Response response) {
                        PreferencesUtil.saveCheckTime(MainActivity.this, System.currentTimeMillis());
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        Log.i("onion", "" + error.toString());
                    }
                });

    }

    /**
     * ?
     */
    private void initView() {
        unreadLabel = (TextView) findViewById(R.id.unread_msg_number);
        unreadAddressLabel = (TextView) findViewById(R.id.unread_address_number);
        tv_newbangbi = (TextView) findViewById(R.id.tv_newbangbi);

        mTabs = new Button[4];
        mTabs[0] = (Button) findViewById(R.id.btn_index);
        mTabs[1] = (Button) findViewById(R.id.btn_conversation);
        mTabs[2] = (Button) findViewById(R.id.btn_address_list);
        mTabs[3] = (Button) findViewById(R.id.btn_setting);
        /**
         * set first label selected
         */
        mTabs[0].setSelected(true);

    }

    /**
     * button
     *
     * @param view
     */
    public void onTabClicked(View view) {
        switch (view.getId()) {
        case R.id.btn_index:
            index = 0;
            refreshIndexUI();
            break;
        case R.id.btn_conversation:
            if (PreferencesUtil.getLogin(MainActivity.this)) {
                refreshUI();
                index = 1;
            } else {
                Intent intent = new Intent(MainActivity.this, RegisterLoginRelationActivity.class);
                startActivity(intent);
            }

            break;
        case R.id.btn_address_list:
            index = 2;
            PreferencesUtil.saveCrazySalesCount(MainActivity.this, 0);
            unreadAddressLabel.setVisibility(View.INVISIBLE);
            // indexFragment.eventService(""+17,"");

            //// 
            //                eventServiceUtils.postClickEvent(currentPagerUUID,"17");
            eventServiceUtils.postScheduleClickEvent(currentPagerUUID, "17");

            break;
        case R.id.btn_setting:
            refreshNewBangBiUI();
            index = 3;
            break;
        }
        if (currentTabIndex != index) {
            viewPager.setCurrentItem(index);
        }
        mTabs[currentTabIndex].setSelected(false);
        /**
         * set current lab selected
         */
        mTabs[index].setSelected(true);
        currentTabIndex = index;
    }

    public void refreshIndexUI() {
        runOnUiThread(new Runnable() {
            public void run() {
                if (indexFragment != null) {
                    indexFragment.refreshIndexMenu();
                }
            }
        });
    }

    public void refreshUI() {
        Log.i("onion", "refreshUI");
        runOnUiThread(new Runnable() {
            public void run() {
                //mChatAllHistoryFProvider.getGroupInfo();
                // bottom bar?
                updateUnreadLabel();
                // ??????
                if (chatHistoryFragment != null) {
                    chatHistoryFragment.refresh();
                }
            }
        });
    }

    public void refreshUI(final String groupId) {
        //        Log.i("onion","refreshUI");
        runOnUiThread(new Runnable() {
            public void run() {
                mChatAllHistoryFProvider.getGroupInfo(groupId);
                // bottom bar?
                updateUnreadLabel();
                // ??????
                if (chatHistoryFragment != null) {
                    chatHistoryFragment.refresh();
                }
            }
        });
    }

    public void refreshNewBangBiUI() {
        runOnUiThread(new Runnable() {
            public void run() {
                // ???
                updateNewbangBi();
            }
        });
    }

    ConnectivityManager mConnectivityManager = null;
    NetworkInfo netInfo = null;
    private BroadcastReceiver myNetReceiver = new BroadcastReceiver() {

        @Override
        public synchronized void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {

                mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                netInfo = mConnectivityManager.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isAvailable()) {
                    if (!isNetwork) {
                        isNetwork = true;

                        //                        PushUtil.isActive(MainActivity.this);

                        //                        AdminUtils.askAdmin(MainActivity.this, "service", null, null);

                        //TODO
                    }
                    Log.i("onion", "");
                    startService(new Intent(context, StatisticAsyncService.class));
                    /////////////
                    String name = netInfo.getTypeName();

                    if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        /////WiFi
                    } else if (netInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                        ///// 303933808@qq.com

                    } else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        /////////3g

                    }
                } else {
                    isNetwork = false;
                    ////////
                    Log.i("onion", "");
                }
            }

        }
    };

    class HomeWatcherReceiver extends BroadcastReceiver {
        private static final String LOG_TAG = TAG;
        private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
        private static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
        private static final String SYSTEM_DIALOG_REASON_LOCK = "lock";
        private static final String SYSTEM_DIALOG_REASON_ASSIST = "assist";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i(LOG_TAG, "onReceive: action: " + action);
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                // android.intent.action.CLOSE_SYSTEM_DIALOGS
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                Log.i(LOG_TAG, "reason: " + reason);

                if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
                    // Home
                    Log.i(LOG_TAG, "homekey");
                    startService(new Intent(getmContext(), StatisticAsyncService.class));
                } else if (SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {
                    // Home  activity?
                    Log.i(LOG_TAG, "long press home key or activity switch");
                } else if (SYSTEM_DIALOG_REASON_LOCK.equals(reason)) {
                    // ??
                    Log.i(LOG_TAG, "lock");
                } else if (SYSTEM_DIALOG_REASON_ASSIST.equals(reason)) {
                    // samsung Home
                    Log.i(LOG_TAG, "assist");
                }

            }
        }

    }

    private HomeWatcherReceiver mHomeKeyReceiver = null;

    private void registerHomeKeyReceiver(Context context) {
        Log.i(TAG, "registerHomeKeyReceiver");
        mHomeKeyReceiver = new HomeWatcherReceiver();
        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        context.registerReceiver(mHomeKeyReceiver, homeFilter);
    }

    private void unregisterHomeKeyReceiver(Context context) {
        Log.i(TAG, "unregisterHomeKeyReceiver");
        if (null != mHomeKeyReceiver) {
            context.unregisterReceiver(mHomeKeyReceiver);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterHomeKeyReceiver(this);

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Log.d(TAG, "onBackPressed : " + this.getClass().getName());
        if (!TextUtils.isEmpty(currentPagerUUID)) {
            Log.d(TAG, "onBackPressed : " + this.getClass().getName() + " currentPagerUUID : " + currentPagerUUID);
            if (eventServiceUtils != null) {
                //// 
                eventServiceUtils.postScheduleExitEvent(currentPagerUUID, this.getClass().getSimpleName());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.i("MainActivity", "onDestroy");

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

        if (homeDialogTimer != null) {
            homeDialogTimer.cancel();
        }

        if (myCommunityCategoryDialog != null) {
            myCommunityCategoryDialog.dismiss();
            myCommunityCategoryDialog = null;
        }

    }

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

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

    /**
     * ???
     */
    public void updateNewbangBi() {

        boolean newBangBi = PreferencesUtil.getNewBangBangBi(this);
        if ((!newBangBi) && (!isVersionUpdate)) {

            tv_newbangbi.setVisibility(View.INVISIBLE);
        } else {

            tv_newbangbi.setVisibility(View.VISIBLE);
        }
        Log.d("updateNewbangBi", "newBangBi) &&(!isVersionUpdate" + ((!newBangBi) && (!isVersionUpdate)));

        //// ????.
        if (tv_newbangbi.getVisibility() != View.VISIBLE) {
            updateBangZhuNews();
        }

        //// ????,?
        if (tv_newbangbi.getVisibility() != View.VISIBLE) {
            updateMyTagsChanges();
        }

    }

    /**
     * ?
     */
    private void updateMyTagsChanges() {

        boolean isUnreadTagsChange = PreferencesUtil.getisUnReadTagsChange(this);
        if (isUnreadTagsChange) {
            Log.d("updateMyTagsChanges", ",??.  " + isUnreadTagsChange);
            if (tv_newbangbi != null) {
                tv_newbangbi.setVisibility(View.VISIBLE);
            }
        }

    }

    /**
     * ??
     */
    public void updateBangZhuNews() {

        String currentTimeStamp = PreferencesUtil.getCurrentBangZhuNewsTimeStamp(this);

        ////?
        boolean bangzhuNews = PreferencesUtil.getCurrentBangzhuNewsReadStatus(this, currentTimeStamp);

        //// ??
        if (PreferencesUtil.getBangzhuUnReadStatus(this) || PreferencesUtil.getInvitedNeighborsUnReadStatus(this)) {

            Log.d("updateBangZhuNews", "getBangzhuUnReadStatus " + PreferencesUtil.getBangzhuUnReadStatus(this));
            Log.d("updateBangZhuNews",
                    "getInvitedNeighborsUnReadStatus " + PreferencesUtil.getInvitedNeighborsUnReadStatus(this));
            Log.d("updateBangZhuNews",
                    "??");

            if (tv_newbangbi != null) {
                tv_newbangbi.setVisibility(View.VISIBLE);
            }
            return;
        }

        Log.d("currentTimeStamp", "" + currentTimeStamp);
        if (TextUtils.isEmpty(currentTimeStamp) || TextUtils.equals(currentTimeStamp, "-1")) {/// new?,?
            if (tv_newbangbi != null) {
                tv_newbangbi.setVisibility(View.INVISIBLE);
            }
            Log.d("currentTimeStamp", "tv_newbangbi.setVisibility(View.INVISIBLE) ");
        } else if (bangzhuNews) { //// ???
            Log.d("bangzhuNews", "???  " + bangzhuNews);

            if (tv_newbangbi != null) {
                tv_newbangbi.setVisibility(View.INVISIBLE);
            }
        } else {
            /// ,??.
            Log.d("bangzhuNews", ",??.  " + bangzhuNews);
            if (tv_newbangbi != null) {
                tv_newbangbi.setVisibility(View.VISIBLE);
            }
        }

    }

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

    }

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

    /**
     * ??
     *
     * @return
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;

        if (PreferencesUtil.getLogin(this) && XjApplication.getInstance().getContactList() != null
                && XjApplication.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME) != null)
            unreadAddressCountTotal = XjApplication.getInstance().getContactList()
                    .get(Constant.NEW_FRIENDS_USERNAME).getUnreadMsgCount();
        return unreadAddressCountTotal;
    }

    /**
     * ??
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;

        if (PreferencesUtil.getLogin(getmContext())) {
            unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
            //// ???
            unreadMsgCountTotal += getAllUnHandleNumsNewFriends();

            Log.d("getUnreadMsgCountTotal ", "unreadMsgCountTotal added  " + unreadMsgCountTotal);
        }

        unreadMsgCountTotal += PreferencesUtil.getWelfareSuccessMsgCount(getmContext());

        Log.d("getUnreadMsgCountTotal ", "unreadMsgCountTotal " + unreadMsgCountTotal + "welfaremsg count :  "
                + PreferencesUtil.getWelfareSuccessMsgCount(getmContext()));

        return unreadMsgCountTotal;
    }

    ArrayList<String> offlineUser = new ArrayList<>();
    // return true ? false?

    /**
     * ?
     */
    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);
            if (offlineUser.contains(from)) {
                XJMessageHelper.loadOffLineMessage(getmContext(),
                        EMChatManager.getInstance().getConversation(from));
                offlineUser.remove(from);
                updateUnreadLabel();
                Log.i("onion", "?");
                return;

            } else if (!XJMessageHelper.operatNewMessage(getmContext(), message)) {
                XJContactHelper.saveContact(message);
                Log.i("onion", "?");
            } else {
                Log.i("onion", "");
                chatHistoryFragment.refresh();
                updateUnreadLabel();
                return;
            }
            if (message.getChatType() == ChatType.GroupChat) {
                GroupHeader header = new Select().from(GroupHeader.class).where("group_id = ?", message.getTo())
                        .executeSingle();
                if (header == null || header.getNum() < 10 || !new File(header.getHeader_id()).exists())
                    GroupUtils.getGroupInfo(message.getTo());
            }
            chatHistoryFragment.refresh();
            //            if(XJMessageHelper.operatNewMessage(message)){abortBroadcast();return;}
            /*  try {
            String strUserInfo = message.getStringAttribute("xj");
            logger.info("xj is :" + message.getStringAttribute("xj"));
            Gson gson = new Gson();
            UserInfoBean userInfoBean = gson.fromJson(strUserInfo, UserInfoBean.class);
            logger.info("nickname is :" + userInfoBean.getUserInfo().getNickname());
            logger.info("avatar is :" + userInfoBean.getUserInfo().getAvatar());
                
              } catch (EaseMobException e) {
            e.printStackTrace();
              }*/

            // 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();
            //
            //todo ?
            //            if(!from.equals("admin")){
            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;
                }
            }

        }
    };

    private static String title = "";//??
    private String content = "";
    private int timestamp = 0;
    /**
     * ??BroadcastReceiver
     */
    private BroadcastReceiver cmdMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();
            //            EMLog.d(TAG, "??");
            //?cmd message
            String msgId = intent.getStringExtra("msgid");
            EMMessage message = intent.getParcelableExtra("message");
            //??body
            CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
            String action = cmdMsgBody.action;// ?action

            //? ?
            try {
                title = message.getStringAttribute("title");
                content = message.getStringAttribute("content");
                timestamp = message.getIntAttribute("timestamp");
            } catch (EaseMobException e) {
                e.printStackTrace();
            }

            //            if("200".equals(code)){
            //                Intent it=new Intent(MainActivity.this,CommentActivity.class);
            //                startActivity(it);
            //                code="";
            //            }
            Log.i(TAG, "form--" + message.getFrom() + "    to--" + message.getTo());
        }
    };

    /**
     * ?BroadcastReceiver sdk ????clientreceiverUI
     * ??? UI ????
     */
    private BroadcastReceiver offlineMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //            XJMessageHelper.loadNativeMessage();
            //            abortBroadcast();
            String[] users = intent.getStringArrayExtra("fromuser");
            String[] groups = intent.getStringArrayExtra("fromgroup");
            Log.i("onion", "users" + users);
            if (users != null) {
                for (String user : users) {
                    //                   XJMessageHelper.loadOffLineMessage(EMChatManager.getInstance().getConversation(user));
                    offlineUser.add(user);
                }
            }
            Log.i("onion", "groups" + groups);
            if (groups != null) {
                for (String group : groups) {
                    GroupHeader header = new Select().from(GroupHeader.class).where("group_id = ?", group)
                            .executeSingle();
                    if (header == null || header.getNum() < 10 || !new File(header.getHeader_id()).exists())
                        GroupUtils.getGroupInfo(group);
                }
            }
            //            chatHistoryFragment.refresh();
            //            updateUnreadLabel();
            //            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 = XjApplication.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 == 2)
            //                contactListFragment.refresh();
        }

        @Override
        public void onContactDeleted(final List<String> usernameList) {
            // 
            Map<String, User> localUsers = XjApplication.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 (currentTabIndex == 2) {

                        //                        contactListFragment.refresh();
                    } else if (currentTabIndex == 1)
                        refreshUI();
                }
            });

        }

        @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 == 2)
        //            contactListFragment.refresh();
    }

    /**
     * ?msg
     *
     * @param msg
     */
    private void saveInviteMsg(InviteMessage msg) {
        // ?msg
        inviteMessgeDao.saveMessage(msg);
        // 1
        User user = XjApplication.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) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.CONNECTION_CONFLICT) {
                        // ??dialog
                        showConflictDialog();
                        //                     boolean flag= PushManager.getInstance().unBindAlias(MainActivity.this,   PreferencesUtil.getLoginInfo(MainActivity.this).getEmobId());
                        //                        PreferencesUtil.Logout(MainActivity.this);
                    } else {
                        Log.d("test", "login error");
                        //                        chatHistoryFragment.errorItem.setVisibility(View.VISIBLE);
                        //                        if (NetUtils.hasNetwork(MainActivity.this))
                        //                            chatHistoryFragment.errorText.setText("???");
                        //                        else
                        //                            chatHistoryFragment.errorText
                        //                                    .setText("???");
                    }
                }

            });
        }
    }

    ////api/v1/communities/{communityId}/users/{emobId}/activities/messages?time={time}

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

        @Override
        public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) {
            //?
            Log.i("MyGroupChangeListener ", "onInvitationReceived " + groupId + groupName + reason);
            for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
                if (group.getGroupId().equals(groupId)) {
                    /// ????
                    return;
                }
            }

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

            try {

                String agreetxt = groupName + "?";
                JSONObject obj = new JSONObject();
                obj.put("groupName", groupName);
                obj.put("groupId", groupId);
                obj.put("inviter", inviter);
                obj.put("reason", agreetxt);

                //                String n_messageId = obj.getString("n_messageId");

                //                String n_messageId = emobIdGroup+"_"+emobGroupOwner+"_"+userBean.getEmobId();
                userInfoBean = PreferencesUtil.getLoginInfo(getmContext());
                String n_messageId = null;
                if (userInfoBean != null) {
                    n_messageId = groupId + "_" + inviter + "_" + userInfoBean.getEmobId();
                    //// 
                    GroupUtils.createEMConversationMessage(getmContext(), obj.toString(), n_messageId,
                            InviteMesageStatus.JOINED);
                }

            } catch (JSONException e) {
                e.printStackTrace();
                Log.d(TAG, e.getMessage());
            }
            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    if (currentTabIndex == 1) {
                        refreshUI();
                    }
                }
            });
        }

        /**
         * @param groupId
         * @param inviter
         * @param reason
         * @"u_userName" : [XJAccountTool account].nickname,
         * @"u_userAvatar" : [XJAccountTool account].avatar,
         * @"n_reason" : alertView.textView.text,
         * @"n_messageId" : message.messageId,
         * @"g_groupOwerEmobId"
         */

        @Override
        public void onInvitationAccpted(String groupId, String inviter, String reason) {
            //??
            Log.i("MyGroupChangeListener", "onInvitationAccpted " + groupId + inviter + reason);
            //
            //            try {
            //                JSONObject obj = new JSONObject();
            //                obj.put("reason",reason);
            //                obj.put("groupId",groupId);
            //                obj.put("inviter",inviter);
            //                obj.put("reason",reason);
            //
            //                String emobid = PreferencesUtil.getLoginInfo(getmContext()).getEmobId();
            //                GroupUtils.createEMConversationMessage(getmContext(),obj.toString(), emobid,InviteMesageStatus.JOINED);
            //
            //            } catch (JSONException e) {
            //                e.printStackTrace();
            //                Log.d(TAG, e.getMessage());
            //            }

        }

        @Override
        public void onInvitationDeclined(String groupId, String invitee, String reason) {
            //??
            //            showToast("onInvitationDeclined "+ reason);

            //            Log.i("MyGroupChangeListener","onInvitationDeclined "+ groupId + invitee + reason);
            //
            //            try {
            //                JSONObject obj = new JSONObject();
            //                obj.put("reason",reason);
            //                obj.put("groupId",groupId);
            //                obj.put("invitee",invitee);
            //
            //                Log.d(TAG, invitee + " ?"  + groupId+ ", reason "+ reason );
            //
            //                String emobid = PreferencesUtil.getLoginInfo(getmContext()).getEmobId();
            //                GroupUtils.createEMConversationMessage(getmContext(),obj.toString(), emobid,InviteMesageStatus.BEREFUSED);
            //
            //            } catch (JSONException e) {
            //                e.printStackTrace();
            //                Log.d(TAG, e.getMessage());
            //            }
        }

        @Override
        public void onUserRemoved(String groupId, String groupName) {
            //???
            // ui

            runOnUiThread(new Runnable() {
                public void run() {
                    try {
                        updateUnreadLabel();
                        if (currentTabIndex == 1)
                            refreshUI();
                        if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                            GroupsActivity.instance.onResume();
                        }
                    } catch (Exception e) {
                        EMLog.e(TAG, "refresh exception " + e.getMessage());
                    }
                }
            });
        }

        @Override
        public void onGroupDestroy(String groupId, String groupName) {
            //?

            //            showToast("onGroupDestroy "+ groupName);

            try {
                JSONObject obj = new JSONObject();
                obj.put("groupName", groupName);
                obj.put("groupId", groupId);

                Log.d(TAG, groupName + " " + " groupId " + groupId);
                //
                //                String emobid = PreferencesUtil.getLoginInfo(getmContext()).getEmobId();
                //                GroupUtils.createEMConversationMessage(getmContext(),obj.toString(), emobid,InviteMesageStatus.AGREED);

            } catch (JSONException e) {
                e.printStackTrace();
                Log.d(TAG, e.getMessage());
            }

            // ??,demo?
            // ui
            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    if (currentTabIndex == 1)
                        refreshUI();
                    if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });
        }

        /**
         * @param groupId
         * @param groupName
         * @param applyer
         * @param reason
         */
        @Override
        public void onApplicationReceived(String groupId, String groupName, String applyer, String reason) {
            //
            try {
                JSONObject obj = new JSONObject(reason);

                //                    jsonObject = jsonObject.put("u_userName", userBean.getNickname());
                //                    jsonObject = jsonObject.put("u_userAvatar", userBean.getAvatar());
                //                    jsonObject = jsonObject.put("n_reason", joinReason);
                //                    jsonObject = jsonObject.put("g_groupOwerEmobId", emobGroupOwner);
                //                    jsonObject = jsonObject.put("n_messageId", n_messageId);

                String joinReason = obj.getString("n_reason");
                String nickname = obj.getString("u_userName");
                String userAvatar = obj.getString("u_userAvatar");
                String g_groupOwerEmobId = obj.getString("g_groupOwerEmobId");
                String n_messageId = obj.getString("n_messageId");

                obj.put("groupName", groupName);
                obj.put("groupId", groupId);
                obj.put("applyerId", applyer);

                Log.d(TAG, nickname + " ?" + groupName + " groupId " + groupId + " reason "
                        + reason);

                //// ?
                GroupUtils.createEMConversationMessage(getmContext(), obj.toString(), n_messageId,
                        InviteMesageStatus.BEAPPLYED);

            } catch (JSONException e) {
                e.printStackTrace();
                Log.d(TAG, e.getMessage());
            }
            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    if (currentTabIndex == 1) {
                        refreshUI();
                    }
                }
            });

            //            // ?
            //            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) {
            //??
            Log.i("MyGroupChangeListener", "onApplicationAccept " + groupId + groupName + accepter);

            //            aff offline group application accetpt received event for group

            try {
                //// msgId
                //                String n_messageId = UUID.randomUUID().toString().replaceAll("-", "");

                userInfoBean = PreferencesUtil.getLoginInfo(getmContext());
                if (userInfoBean != null) {
                    /////
                    String n_messageId = groupId + "_" + accepter + "_" + userInfoBean.getEmobId();

                    JSONObject obj = new JSONObject();
                    obj.put("groupName", groupName);
                    obj.put("groupId", groupId);
                    obj.put("accepter", accepter);
                    Log.d(TAG, groupName + " ???" + " groupId " + groupId);

                    GroupUtils.createEMConversationMessage(getmContext(), obj.toString(), n_messageId,
                            InviteMesageStatus.BEAGREED);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            updateUnreadLabel();
                            // ui
                            if (currentTabIndex == 1)
                                refreshUI();
                        }
                    });

                    try {
                        EMGroupManager.getInstance().getGroupsFromServer();
                    } catch (EaseMobException e) {
                        e.printStackTrace();
                    }

                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.d(TAG, e.getMessage());
            }

        }

        @Override
        public void onApplicationDeclined(String groupId, String groupName, String decliner, String reason) {
            // ?
            Log.i("onApplicationDeclined", groupId + groupName + reason + decliner);
            if (userInfoBean != null && TextUtils.equals(decliner, userInfoBean.getEmobId())) {
                return;
            }

            try {

                JSONObject jsonObject = new JSONObject(reason);

                //                jsonObject.put("u_userName", nickname);
                //                jsonObject.put("u_userAvatar", userAvatar);
                //                jsonObject.put("n_reason", declineReason);
                //                jsonObject.put("n_messageId", n_messageId);
                //                jsonObject.put("g_groupId", groupId);
                //                jsonObject.put("g_groupname", groupName);
                //                jsonObject.put("g_groupOwerEmobId", g_groupOwerEmobId);

                jsonObject.put("groupName", groupName);
                jsonObject.put("groupId", groupId);
                jsonObject.put("decliner", decliner);

                String n_messageId = jsonObject.getString("n_messageId");

                Log.d(TAG, decliner + " ?" + groupName + " groupId " + groupId + " reason " + reason);

                GroupUtils.createEMConversationMessage(getmContext(), jsonObject.toString(), n_messageId,
                        InviteMesageStatus.BEREFUSED);

            } catch (JSONException e) {
                e.printStackTrace();
                Log.d(TAG, e.getMessage());
            }
            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    // ui
                    if (currentTabIndex == 1)
                        refreshUI();
                }
            });
        }

    }

    public int getAllUnHandleNumsNewFriends() {

        if (EMChatManager.getInstance() != null && PreferencesUtil.getLogin(getmContext())) {
            EMConversation conversation = EMChatManager.getInstance()
                    .getConversation(Constant.NEW_FRIENDS_USERNAME);
            List<EMMessage> allMessages = conversation.getAllMessages();
            int unhandleNums = 0;

            for (EMMessage message : allMessages) {
                try {
                    String isHandle = message.getStringAttribute(Config.EXPKey_ishandle);
                    if ("n".equals(isHandle)) {
                        unhandleNums++;
                    }
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }

            Log.d("getAllUnHandleNumsNewFriends ", "unhandleNums " + unhandleNums);
            return unhandleNums;
        }
        return 0;
    }

    /**
     * indexFragment.refreshIndexMenu();
     * indexFragment.getLifeCircleCount(handler);
     */

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);

        if (!isConflict) {
            //            updateUnreadLabel();
            //            updateUnreadAddressLable();
            EMChatManager.getInstance().activityResumed();
            refreshUI();
            refreshNewBangBiUI();
        }
        // unregister this event listener when this activity enters the
        // background
        HXSDKHelper sdkHelper = (HXSDKHelper) HXSDKHelper.getInstance();
        sdkHelper.pushActivity(this);
        EMChatManager.getInstance().registerEventListener(this,
                new EMNotifierEvent.Event[] { EMNotifierEvent.Event.EventNewMessage,
                        EMNotifierEvent.Event.EventDeliveryAck, EMNotifierEvent.Event.EventOfflineMessage,
                        EMNotifierEvent.Event.EventConversationListChanged });

        initNotifyCount();

        viewPager.setCurrentItem(index);

        //        if (Config.PHONETYPE.equals(android.os.Build.MANUFACTURER)) {
        //// 2015/12/2 ?? ?????
        XjApplication.getInstance().pool.submit(new Runnable() {
            @Override
            public void run() {
                startService(new Intent(getmContext(), PushPullReqService.class));
            }
        });
        //        }

        registerHomeKeyReceiver(this);

    }

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

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

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

    /**
     * ??dialog
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        final UserInfoDetailBean detailBean = PreferencesUtil.getLoginInfo(getApplication());
        username = detailBean.getUsername();
        password = detailBean.getPassword();
        final XJUserInfoBean bean = new XJUserInfoBean();
        bean.setInfo(detailBean);

        if (xjpushManager != null) {
            xjpushManager.unregisterLoginedPushService();
        } else {
            xjpushManager = new XJPushManager(this);
            xjpushManager.unregisterLoginedPushService();
        }

        //        boolean flag= PushManager.getInstance().unBindAlias(MainActivity.this,   PreferencesUtil.getLoginInfo(MainActivity.this).getEmobId());
        //        Log.i("onion","flag"+flag);
        XjApplication.getInstance().logout(new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshUI();
                        refreshNewBangBiUI();
                    }
                });
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
        PreferencesUtil.Logout(MainActivity.this);
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                final Dialog dialog = new Dialog(MainActivity.this, R.style.MyDialogStyle);
                dialog.setContentView(R.layout.dialog_conflict);
                TextView tv_cancle = (TextView) dialog.findViewById(R.id.tv_cancle);
                TextView tv_relogin = (TextView) dialog.findViewById(R.id.tv_relogin);
                tv_cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        conflictBuilder = null;
                        dialog.dismiss();
                        index = 0;
                        updateUnreadLabel();
                        startActivity(new Intent(MainActivity.this, MainActivity.class));
                        //                        finish();
                    }
                });
                tv_relogin.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final ProgressDialog pd = new ProgressDialog(MainActivity.this,
                                ProgressDialog.THEME_HOLO_LIGHT);
                        pd.setCanceledOnTouchOutside(false);
                        pd.setCancelable(false);
                        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {

                            @Override
                            public void onCancel(DialogInterface dialog) {
                                progressShow = false;
                            }
                        });
                        progressShow = true;
                        pd.setMessage("...");
                        if (pd != null && !MainActivity.this.isFinishing())
                            pd.show();
                        //???
                        // getuser((int) detailBean.getCommunityId(),detailBean.getEmobId());
                        UserUtils.reLoginUser(MainActivity.this, username, password, new Handler() {
                            @Override
                            public void handleMessage(Message msg) {
                                switch (msg.what) {
                                case Config.LoginUserComplete:
                                    if (progressShow)
                                        pd.dismiss();
                                    dialog.dismiss();
                                    startActivity(new Intent(MainActivity.this, MainActivity.class));
                                    isConflict = false;

                                    //                                        boolean flag = PushManager.getInstance().bindAlias(MainActivity.this, PreferencesUtil.getLoginInfo(MainActivity.this).getEmobId());
                                    PushManager.getInstance().turnOnPush(MainActivity.this);

                                    if (xjpushManager == null) {
                                        xjpushManager = new XJPushManager(getmContext());
                                    }
                                    xjpushManager.registerLoginedPushService();
                                    break;
                                case Config.LoginUserFailure:
                                    if (progressShow && !MainActivity.this.isFinishing()) {
                                        pd.dismiss();
                                        Toast.makeText(MainActivity.this, "?", Toast.LENGTH_SHORT)
                                                .show();
                                    }
                                    break;
                                default:
                                    pd.setMessage("..");
                                    break;

                                }
                            }
                        });

                        /* UserUtils.loginEMChat(MainActivity.this, username, bean, new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            switch (msg.what) {
                                case Config.LoginUserComplete:
                                    if (progressShow) pd.dismiss();
                                    dialog.dismiss();
                                    UserUtils.appLogin(MainActivity.this,PushManager.getInstance().getClientid(MainActivity.this), PreferencesUtil.getLoginInfo(MainActivity.this).getUsername());
                                    startActivity(new Intent(MainActivity.this,
                                        MainActivity.class));
                                    isConflict=false;
                                    boolean flag= PushManager.getInstance().bindAlias(MainActivity.this,   PreferencesUtil.getLoginInfo(MainActivity.this).getEmobId());
                            
                                    PushManager.getInstance().turnOnPush(MainActivity.this);
                                    break;
                                case Config.LoginUserFailure:
                                    if (progressShow && !MainActivity.this.isFinishing()) {
                                        pd.dismiss();
                                        Toast.makeText(MainActivity.this, "?", Toast.LENGTH_SHORT).show();
                                    }
                                    break;
                                default:
                                    pd.setMessage("..");
                                    break;
                            
                            }
                        }
                         });*/
                    }
                });

                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
                dialog.setCancelable(false);
                dialog.show();

                isConflict = true;
            } catch (Exception e) {
                EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage());
            }

        }
    }

    interface GetUserService {
        @GET("/api/v1/communities/{communityId}/users/{emobId}")
        void getuser(@Path("communityId") int communityId, @Path("emobId") String emobId,
                Callback<XJUserInfoBean> cb);

        @GET("/api/v1/communities/{communityId}/labels/random")
        void getCommunityCategoryData(@Path("communityId") long communityId,
                Callback<CommunityCategoryDataRespBean> cb);

    }

    MyCommunityCategoryDialog myCommunityCategoryDialog = null;

    private void fetchCommunityCategoryData() {
        RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Config.NET_BASE).build();
        restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);
        GetUserService isUserExistService = restAdapter.create(GetUserService.class);
        Callback<CommunityCategoryDataRespBean> callback = new Callback<CommunityCategoryDataRespBean>() {
            @Override
            public void success(CommunityCategoryDataRespBean bean, Response response) {
                if (bean != null && "yes".equals(bean.getStatus())) {
                    List<CommunityCategoryDataRespBean.InfoEntity> info = bean.getInfo();
                    if (info != null && info.size() > 0) {

                        myCommunityCategoryDialog = new MyCommunityCategoryDialog(getmContext(), info);
                        myCommunityCategoryDialog.setCanceledOnTouchOutside(true);
                        myCommunityCategoryDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                PreferencesUtil.setFirstOpen(getmContext(), false);
                            }
                        });

                        //                        WindowManager windowManager = getWindowManager();
                        //                        Display display = windowManager.getDefaultDisplay();

                        //                        2015/12/18 start

                        //                        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
                        //                        Window window = myCommunityCategoryDialog.getWindow();
                        //                        lp.copyFrom(window.getAttributes());
                        //
                        //                        lp.width = DensityUtil.dip2px(getmContext(),360f);
                        //                        lp.height = DensityUtil.dip2px(getmContext(),641f);
                        //                        window.setAttributes(lp);
                        //                        2015/12/18 end

                        //                        WindowManager manager = (WindowManager) getSystemService(Activity.WINDOW_SERVICE);
                        //                        int width, height;
                        //
                        //                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
                        //                            width = manager.getDefaultDisplay().getWidth();
                        //                            height = manager.getDefaultDisplay().getHeight();
                        //                        } else {
                        //                            Point point = new Point();
                        //                            manager.getDefaultDisplay().getSize(point);
                        //                            width = point.x;
                        //                            height = point.y;
                        //                        }
                        //                        lp.width = width;
                        //                        lp.height = height;

                        //                        WindowManager.LayoutParams lp = myCommunityCategoryDialog.getWindow().getAttributes();
                        //                        lp.width = getmContext().getResources().getDisplayMetrics().widthPixels;
                        //                        myCommunityCategoryDialog.getWindow().setAttributes(lp);

                        myCommunityCategoryDialog.show();
                        homeDialogTimer = new CountDownTimer(DIALOG_SHOW_TIME, 1000) {
                            @Override
                            public void onTick(long millisUntilFinished) {
                            }

                            @Override
                            public void onFinish() {
                                myCommunityCategoryDialog.dismiss();
                            }
                        };
                        homeDialogTimer.start();

                    }
                }
                PreferencesUtil.setFirstOpen(getmContext(), false);
            }

            @Override
            public void failure(RetrofitError error) {
                PreferencesUtil.setFirstOpen(getmContext(), false);
            }
        };

        long communityId;
        if (PreferencesUtil.getLogin(this)) {
            communityId = PreferencesUtil.getLoginInfo(this).getCommunityId();
        } else {
            communityId = PreferencesUtil.getCommityId(this);
        }
        isUserExistService.getCommunityCategoryData(communityId, callback);
    }

    CountDownTimer homeDialogTimer = null;

    private void getuser(int communityId, String emobId) {
        RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Config.NET_BASE2).build();
        GetUserService isUserExistService = restAdapter.create(GetUserService.class);
        Callback<XJUserInfoBean> callback = new Callback<XJUserInfoBean>() {
            @Override
            public void success(XJUserInfoBean bean, Response response) {
                PreferencesUtil.Logout(MainActivity.this);
                PreferencesUtil.saveLogin(MainActivity.this, bean.getInfo());
                Map<String, User> map = new HashMap<String, User>();
                XjApplication.getInstance().setContactList(map);
            }

            @Override
            public void failure(RetrofitError error) {

                showNetErrorToast();
            }
        };
        isUserExistService.getuser(communityId, emobId, callback);
    }

    interface GetGroupInfoMsgService {
        //        @GET("/api/v1/communities/{communityId}/users/{emobId}/activities/messages")
        //        void getgroupMsgs(@Path("communityId") int communityId, @Path("emobId") String emobId, @QueryMap Map<String, String> map, Callback<GroupMsgRespBean> cb);
        //        @GET("/api/v1/communities/{communityId}/users/{emobId}/activities/messages")

        ////api/v3/activities/messages?emobIdUser={?ID}&time={??}
        @GET("/api/v3/activities/messages")
        void getgroupMsgs(@QueryMap Map<String, String> map, Callback<CommonRespBean<List<GroupMsgInfoBean>>> cb);
    }

    private void getGroupMsgsCall(int communityId, String emobId) {

        int lastReqGroupInfosTime = PreferencesUtil.getLastReqGroupInfosTime(getmContext());
        if (lastReqGroupInfosTime == 0) {
            lastReqGroupInfosTime = (int) (System.currentTimeMillis() / 1000);
        }
        PreferencesUtil.setLastReqGroupInfosTime(getmContext(), (int) (System.currentTimeMillis() / 1000));
        HashMap<String, String> option = new HashMap<String, String>();
        option.put("time", "" + lastReqGroupInfosTime);
        option.put("emobIdUser", "" + emobId);

        GetGroupInfoMsgService isUserExistService = RetrofitFactory.getInstance().create(getmContext(), option,
                GetGroupInfoMsgService.class);
        Callback<CommonRespBean<List<GroupMsgInfoBean>>> callback = new Callback<CommonRespBean<List<GroupMsgInfoBean>>>() {
            @Override
            public void success(final CommonRespBean<List<GroupMsgInfoBean>> bean, Response response) {

                if (bean != null && TextUtils.equals("yes", bean.getStatus()) && bean.getData() != null) {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            processingGroupMsgDuplicate(bean.getData());
                        }
                    }).start();
                } else {
                    Log.d("processingGroupMsgDuplicate ", "info is null ");
                }
            }

            @Override
            public void failure(RetrofitError error) {
                error.printStackTrace();
            }
        };

        isUserExistService.getgroupMsgs(option, callback);
    }

    private void processingGroupMsgDuplicate(List<GroupMsgInfoBean> info) {
        Log.d("processingGroupMsgDuplicate ", "process start ! ");
        if (info == null || info.size() <= 0) {
            Log.d("processingGroupMsgDuplicate ", "info is null ");
            return;
        }

        if (EMChatManager.getInstance() != null && PreferencesUtil.getLogin(getmContext())) {
            EMConversation conversation = EMChatManager.getInstance()
                    .getConversation(Constant.NEW_FRIENDS_USERNAME);
            List<EMMessage> allMessages = conversation.getAllMessages();

            if (allMessages != null && allMessages.size() > 0) {
                Log.d("processingGroupMsgDuplicate ", "allMessages size is  " + allMessages.size());
                List<EMMessage> load = conversation.loadMoreMsgFromDB(allMessages.get(0).getMsgId(), 20);
                allMessages.addAll(load);
                processingSubMsgDuplicate(info, allMessages);

            } else {
                processingSubMsgDuplicate(info, allMessages);
            }
        }
        Log.d("processingGroupMsgDuplicate ", "process end ! ");

    }

    private void processingSubMsgDuplicate(List<GroupMsgInfoBean> info, List<EMMessage> allMessages) {

        long communityId = PreferencesUtil.getLoginInfo(this).getCommunityId();
        String emobId = PreferencesUtil.getLoginInfo(this).getEmobId();

        for (GroupMsgInfoBean infoBean : info) {
            ////TODO check  ???
            if (notExists(infoBean, allMessages)) {
                String messageContent = infoBean.getMessageContent();

                String type = infoBean.getType();
                if (TextUtils.equals(type, "apply")) {
                    try {

                        JSONObject obj = new JSONObject();

                        //                    jsonObject = jsonObject.put("u_userName", userBean.getNickname());
                        //                    jsonObject = jsonObject.put("u_userAvatar", userBean.getAvatar());
                        //                    jsonObject = jsonObject.put("n_reason", joinReason);
                        //                    jsonObject = jsonObject.put("g_groupOwerEmobId", emobGroupOwner);
                        //                    jsonObject = jsonObject.put("n_messageId", n_messageId);

                        obj.put("u_userName", infoBean.getFromNickname());
                        obj.put("u_userAvatar", infoBean.getFromAvatar());
                        obj.put("n_reason", infoBean.getMessageContent());
                        obj.put("g_groupOwerEmobId", emobId);
                        obj.put("n_messageId", infoBean.getMessageId());

                        obj.put("groupName", infoBean.getGroupName());
                        obj.put("groupId", infoBean.getGroupId());
                        obj.put("applyerId", infoBean.getEmobIdFrom());

                        String joinReason = obj.optString("n_reason");
                        String nickname = obj.getString("u_userName");
                        String userAvatar = obj.getString("u_userAvatar");
                        String g_groupOwerEmobId = obj.getString("g_groupOwerEmobId");
                        String n_messageId = obj.getString("n_messageId");

                        Log.d(TAG, nickname + " ?" + infoBean.getGroupName() + " groupId "
                                + infoBean.getGroupId() + " reason " + messageContent);

                        //// ?
                        GroupUtils.createEMConversationMessage(getmContext(), obj.toString(), n_messageId,
                                InviteMesageStatus.BEAPPLYED);

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.d(TAG, e.getMessage());
                    }
                    runOnUiThread(new Runnable() {
                        public void run() {
                            updateUnreadLabel();
                            if (currentTabIndex == 1) {
                                refreshUI();
                            }
                        }
                    });

                } else if (TextUtils.equals(type, "accept")) {

                    userInfoBean = PreferencesUtil.getLoginInfo(getmContext());
                    if (userInfoBean != null) {
                        try {
                            //// msgId
                            //                                String n_messageId = UUID.randomUUID().toString().replaceAll("-", "");

                            //                                    String n_messageId = infoBean.getGroupId()+"_"+infoBean.getEmobIdFrom()+"_"+userInfoBean.getEmobId();

                            JSONObject obj = new JSONObject();
                            obj.put("groupName", infoBean.getGroupName());
                            obj.put("groupId", infoBean.getGroupId());
                            obj.put("accepter", infoBean.getEmobIdFrom());
                            Log.d(TAG,
                                    infoBean.getGroupName() + " ???" + " groupId " + info);
                            GroupUtils.createEMConversationMessage(getmContext(), obj.toString(),
                                    infoBean.getMessageId(), InviteMesageStatus.BEAGREED);

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.d(TAG, e.getMessage());
                        }
                        runOnUiThread(new Runnable() {
                            public void run() {
                                updateUnreadLabel();
                                // ui
                                if (currentTabIndex == 1)
                                    refreshUI();
                            }
                        });
                    }

                } else if (TextUtils.equals(type, "reject")) {

                    userInfoBean = PreferencesUtil.getLoginInfo(getmContext());
                    if (userInfoBean != null) {

                        try {

                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("groupName", infoBean.getGroupName());
                            jsonObject.put("groupId", infoBean.getGroupId());
                            jsonObject.put("decliner", infoBean.getEmobIdFrom());
                            jsonObject.put("n_reason", infoBean.getMessageContent());
                            jsonObject.put("u_userName", infoBean.getFromNickname());
                            jsonObject.put("u_userAvatar", infoBean.getFromAvatar());
                            ////todo 2016/1/7 groupownerid
                            jsonObject.put("g_groupOwerEmobId", infoBean.getEmobIdFrom());
                            jsonObject.put("n_messageId", infoBean.getMessageId());

                            String n_messageId = infoBean.getMessageId();

                            //                                String n_messageId = jsonObject.getString("n_messageId");

                            Log.d(TAG, infoBean.getGroupName() + " ?" + infoBean.getGroupName()
                                    + " groupId " + infoBean.getGroupId() + " reason " + messageContent);

                            GroupUtils.createEMConversationMessage(getmContext(), jsonObject.toString(),
                                    n_messageId, InviteMesageStatus.BEREFUSED);

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.d(TAG, e.getMessage());
                        }
                        runOnUiThread(new Runnable() {
                            public void run() {
                                updateUnreadLabel();
                                // ui
                                if (currentTabIndex == 1)
                                    refreshUI();
                            }
                        });
                    }
                }
            }
        }

    }

    private boolean notExists(GroupMsgInfoBean infoBean, List<EMMessage> allMessages) {
        if (allMessages == null || allMessages.size() <= 0) {
            Log.d("processingGroupMsgDuplicate ", "local allMessages is null notExists  :" + infoBean);
            return true;
        }

        for (EMMessage message : allMessages) {
            if (TextUtils.equals(message.getMsgId(), infoBean.getMessageId())) {
                return false;
            }
        }
        Log.d("processingGroupMsgDuplicate ", "notExists  :" + infoBean);
        return true;
    }

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

    private boolean equalsVersion(String serviceVersion, String localVersion) {
        //        Log.i("equalsVersion","serviceVersion"+serviceVersion);
        //        Log.i("equalsVersion","localVersion"+localVersion);
        boolean b = false;
        int serviceint, localint;
        String[] serviceVersions = serviceVersion.split("\\.");
        String[] loaclVersions = localVersion.split("\\.");
        for (int i = 0; i < serviceVersions.length; i++) {
            serviceint = Integer.parseInt(serviceVersions[i]);
            localint = Integer.parseInt(loaclVersions[i]);
            //            Log.i("equalsVersion","serviceint"+serviceint);
            if (serviceint > localint) {
                b = true;
                break;
            } else if (serviceint < localint) {
                b = false;
                break;
            }
        }
        return b;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                Log.i("debbug", "" + PreferencesUtil.getCrazySalesCount(MainActivity.this));
                if (PreferencesUtil.getCrazySalesCount(MainActivity.this) == 0) {
                    unreadAddressLabel.setVisibility(View.INVISIBLE);
                } else {
                    unreadAddressLabel.setVisibility(View.VISIBLE);
                    unreadAddressLabel.setText("" + PreferencesUtil.getCrazySalesCount(MainActivity.this));
                }

            }
        }
    };

    //    String records = null;
    //    StringBuilder recordBuilder = null;
    //
    //    public void getRecords(ContentResolver contentResolver) {
    //        // ContentResolver contentResolver = getContentResolver();
    //        Cursor cursor = contentResolver.query(
    //                Uri.parse("content://browser/bookmarks"), new String[] {
    //                        "title", "url", "date" }, "date!=?",
    //                new String[] { "null" }, "date desc");
    //        while (cursor != null && cursor.moveToNext()) {
    //            String url = null;
    //            String title = null;
    //            String time = null;
    //            String date = null;
    //
    //            recordBuilder = new StringBuilder();
    //            title = cursor.getString(cursor.getColumnIndex("title"));
    //            url = cursor.getString(cursor.getColumnIndex("url"));
    //
    //            date = cursor.getString(cursor.getColumnIndex("date"));
    //
    //            SimpleDateFormat dateFormat = new SimpleDateFormat(
    //                    "yyyy-MM-dd hh:mm;ss");
    //            Date d = new Date(Long.parseLong(date));
    //            time = dateFormat.format(d);
    //
    //            System.out.println(title + url + time);
    //        }
    //    }

}