com.ccxt.whl.activity.MainActivity_0903.java Source code

Java tutorial

Introduction

Here is the source code for com.ccxt.whl.activity.MainActivity_0903.java

Source

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
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.easemob.chat.ConnectionListener;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.EMMessage.Type;
import com.easemob.chat.EMNotifier;
import com.easemob.chat.GroupChangeListener;
import com.easemob.chat.TextMessageBody;
import com.ccxt.whl.Constant;
import com.ccxt.whl.DemoApplication;
import com.ccxt.whl.R;
import com.ccxt.whl.activity.ZainaFragment.OnMySelectedListener;
import com.ccxt.whl.db.InviteMessgeDao;
import com.ccxt.whl.db.UserDao;
import com.ccxt.whl.domain.InviteMessage;
import com.ccxt.whl.domain.User;
import com.ccxt.whl.domain.InviteMessage.InviteMesageStatus;
import com.ccxt.whl.utils.CommonUtils;
import com.ccxt.whl.utils.HttpRestClient;
import com.ccxt.whl.utils.JsonToMapList;
import com.easemob.util.HanziToPinyin;
import com.easemob.util.NetUtils;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class MainActivity_0903 extends FragmentActivity implements OnMySelectedListener {

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

    private Button[] mTabs;
    private ZainaFragment zainaFrament;// ?
    private Zaina_gushi_Fragment gushiFrament;//?
    //   private ChatHistoryFragment chatHistoryFragment;
    private ChatAllHistoryFragment chatHistoryFragment;//??
    private ContactlistFragment contactListFragment;//?? 
    private SettingsFragment settingFragment;//?
    private Fragment[] fragments;
    private int index;
    private RelativeLayout[] tab_containers;
    // ?fragmentindex
    private int currentTabIndex;
    private NewMessageBroadcastReceiver msgReceiver;
    // ?
    private boolean isConflict = false;

    private String nickname;
    private String headurl;

    /***loadcontact****/
    private String nickname_tmp = "";
    private String headurl_tmp = "";

    private final static int ZAINAFRAMENT = 0;
    private final static int GUSHIFRAMENT = 0;
    private final static int CHATHISTORYFRAGMENT = 0;
    private final static int CONTACTLISTFRAGMENT = 0;
    private final static int SETTINGFRAGMENT = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //?
        DemoApplication.currentUserNick = DemoApplication.getInstance().getUsernNickName();
        initView();
        inviteMessgeDao = new InviteMessgeDao(this);
        userDao = new UserDao(this);

        zainaFrament = new ZainaFragment();
        gushiFrament = new Zaina_gushi_Fragment();
        //fragment???
        //      chatHistoryFragment = new ChatHistoryFragment();
        //?fragment
        chatHistoryFragment = new ChatAllHistoryFragment();
        contactListFragment = new ContactlistFragment();
        settingFragment = new SettingsFragment();
        //fragments = new Fragment[] { chatHistoryFragment, contactListFragment, settingFragment };
        fragments = new Fragment[] { zainaFrament, gushiFrament, chatHistoryFragment, contactListFragment,
                settingFragment };

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

        // ?BroadcastReceiver
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);

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

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

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

    /**
     * loginactivity??db
     */
    private void loadcontact() {
        // TODO Auto-generated method stub
        new Thread(new Runnable() {
            public void run() {
                Map<String, User> userlists = new HashMap<String, User>();
                userlists = DemoApplication.getInstance().getContactList();
                if (userlists.size() < 2) {
                    return;
                }
                final UserDao dao = new UserDao(MainActivity_0903.this);
                List<User> users = new ArrayList<User>(userlists.values());
                //if(users.l)
                for (final User user : users) {
                    if (user.getUsername().equals(Constant.NEW_FRIENDS_USERNAME)
                            || user.getUsername().equals(Constant.GROUP_USERNAME)) {
                        dao.saveContact(user);
                        Log.d(TAG, "NEW_FRIENDS_USERNAME-pass");
                        continue;//
                    }
                    User local_user_is = dao.getUser(user.getUsername());
                    //?
                    if (!CommonUtils.isNullOrEmpty(local_user_is.toString())) {
                        if (local_user_is.getHeaderurl() != null && local_user_is.getNick() != null
                                && local_user_is.getIs_stranger().equals("2")) {
                            Log.d(TAG, "local_user_is-pass");
                            continue;//
                        }
                    }
                    //???id?
                    if (CommonUtils.isNullOrEmpty(user.getUsername())
                            || CommonUtils.isNullOrEmpty(user.getHeaderurl())
                            || CommonUtils.isNullOrEmpty(user.getNick())) {

                        String httpUrl = Constant.BASE_URL + Constant.USER_URL_C + "user=" + user.getUsername();
                        // httpRequest
                        HttpGet httpRequest = new HttpGet(httpUrl);
                        try {
                            // ?HttpClient
                            HttpClient httpclient = new DefaultHttpClient();
                            // HttpClient?HttpResponse
                            HttpResponse httpResponse = httpclient.execute(httpRequest);
                            // ?
                            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                                // ?
                                String strResult = EntityUtils.toString(httpResponse.getEntity());
                                if (!CommonUtils.isNullOrEmpty(strResult)) {
                                    Map<String, Object> lm = JsonToMapList.getMap(strResult);
                                    if (lm.get("status").toString() != null
                                            && lm.get("status").toString().equals("yes")) {
                                        if (!CommonUtils.isNullOrEmpty(lm.get("result").toString())) {
                                            Map<String, Object> result = JsonToMapList
                                                    .getMap(lm.get("result").toString());
                                            nickname_tmp = result.get("nickname").toString();
                                            headurl_tmp = result.get("headurl").toString();
                                            Log.d(TAG, "nickname_tmp and headurl_tmp " + nickname_tmp + " "
                                                    + headurl_tmp);
                                            /*User user_temp =  new User();
                                             user_temp.setUsername(user.getUsername());
                                             user_temp.setNick(nickname_tmp);
                                             user_temp.setHeaderurl(headurl_tmp); 
                                             dao.saveContact(user_temp);*/
                                        }
                                    }
                                }

                                if (!CommonUtils.isNullOrEmpty(nickname_tmp)
                                        && !CommonUtils.isNullOrEmpty(headurl_tmp)) {
                                    User user_temp = new User();
                                    user_temp.setUsername(user.getUsername());
                                    user_temp.setNick(nickname_tmp);
                                    user_temp.setHeaderurl(headurl_tmp);

                                    dao.saveContact(user_temp);
                                    Log.d(TAG, "saveContact have");
                                } /*else{
                                    User local_user = dao.getUser(user.getUsername());
                                   //?
                                   if(!CommonUtils.isNullOrEmpty(local_user.toString())){
                                      if(!CommonUtils.isNullOrEmpty(local_user.getHeaderurl())
                                  &&!CommonUtils.isNullOrEmpty(local_user.getNick())){
                                         //local_user
                                      }
                                   }else{//?? (??)
                                      if (user.getUsername().equals(Constant.NEW_FRIENDS_USERNAME) || user.getUsername().equals(Constant.GROUP_USERNAME)) {
                                         //user.setHeader("");
                                         dao.saveContact(user);
                                      }else{
                                         user.setNick("");
                                         dao.saveContact(user);
                                         Log.d(TAG,"saveContact not have");
                                      }
                                          
                                   }
                                  }*/
                            }

                        } catch (ClientProtocolException e) {
                            Log.d(TAG, e.getMessage().toString());
                        } catch (IOException e) {
                            Log.d(TAG, e.getMessage().toString());
                        } catch (Exception e) {
                            Log.d(TAG, e.getMessage().toString());
                        }
                        /*RequestParams params = new RequestParams(); 
                        params.add("user", user.getUsername());
                        HttpRestClient.get(Constant.USER_URL_C, params, new BaseJsonHttpResponseHandler(){
                                
                           @Override
                           public void onSuccess(int statusCode, Header[] headers,
                                 String rawJsonResponse, Object response) {
                              // TODO Auto-generated method stub
                              Log.d("rawJsonResponse", rawJsonResponse); 
                              if(!CommonUtils.isNullOrEmpty(rawJsonResponse)){
                                 Map<String, Object> lm = JsonToMapList.getMap(rawJsonResponse);
                                 if(lm.get("status").toString() != null && lm.get("status").toString().equals("yes")){
                          if(!CommonUtils.isNullOrEmpty(lm.get("result"))){ 
                             Map<String, Object> result = JsonToMapList.getMap(lm.get("result").toString());
                             nickname_tmp = result.get("nickname").toString();
                             headurl_tmp = result.get("headurl").toString(); 
                             Log.d(TAG,"nickname_tmp and headurl_tmp "+nickname_tmp+" "+headurl_tmp);
                                  
                          } 
                                 } 
                              } 
                                  
                              if(!CommonUtils.isNullOrEmpty(nickname_tmp)&&!CommonUtils.isNullOrEmpty(headurl_tmp)){
                        User user_temp =  new User();
                        user_temp.setUsername(user.getUsername());
                        user_temp.setNick(nickname);
                        user_temp.setHeaderurl(headurl);
                                     
                        dao.saveContact(user_temp);
                        Log.d(TAG,"saveContact have");
                               }else{
                        User local_user = dao.getUser(user.getUsername());
                                 //?
                                 if(!CommonUtils.isNullOrEmpty(local_user.toString())){
                          if(!CommonUtils.isNullOrEmpty(local_user.getHeaderurl())
                                &&!CommonUtils.isNullOrEmpty(local_user.getNick())){
                             //local_user
                          }
                                 }else{//??
                          user.setNick("");
                          dao.saveContact(user);
                          Log.d(TAG,"saveContact not have");
                                 }
                               }
                                  
                           }
                            
                           @Override
                           public void onFailure(int statusCode, Header[] headers,
                                 Throwable throwable, String rawJsonData,
                                 Object errorResponse) {
                              // TODO Auto-generated method stub 
                           }
                            
                           @Override
                           protected Object parseResponse(String rawJsonData,
                                 boolean isFailure) throws Throwable {
                              // TODO Auto-generated method stub
                              return null;
                           }
                               
                        });*/
                    }
                }

                /**????
                User local_user = dao.getUser(user.getUsername());
                //?
                if(!CommonUtils.isNullOrEmpty(local_user.toString())){
                   if(local_user.getHeaderurl()!=null&&local_user.getNick()!=null){
                     
                   }
                }*/

            }
            //dao.saveContactList(users); 
        }).start();
    }

    /**
     * ?
     */
    private void initView() {
        unreadLabel = (TextView) findViewById(R.id.unread_msg_number);
        unreadAddressLable = (TextView) findViewById(R.id.unread_address_number);
        /*mTabs = new Button[3];
        mTabs[0] = (Button) findViewById(R.id.btn_conversation);
        mTabs[1] = (Button) findViewById(R.id.btn_address_list);
        mTabs[2] = (Button) findViewById(R.id.btn_setting);*/
        mTabs = new Button[5];
        mTabs[0] = (Button) findViewById(R.id.btn_conversation_zaina);//
        mTabs[1] = (Button) findViewById(R.id.btn_gushi);//
        mTabs[2] = (Button) findViewById(R.id.btn_conversation);//?
        mTabs[3] = (Button) findViewById(R.id.btn_address_list);//?
        mTabs[4] = (Button) findViewById(R.id.btn_setting);//
        // tab?
        mTabs[0].setSelected(true);

    }

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

    /**
     * ?fragment
     * @param index
     */
    public void change_f(int index) {

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

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 
        try {
            unregisterReceiver(msgReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(ackMessageReceiver);
        } catch (Exception e) {
        }
        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 updateUnreadAddressLable() {
        runOnUiThread(new Runnable() {
            public void run() {
                int count = getUnreadAddressCountTotal();
                if (count > 0) {
                    unreadAddressLable.setText(String.valueOf(count));
                    unreadAddressLable.setVisibility(View.VISIBLE);
                } else {
                    unreadAddressLable.setVisibility(View.INVISIBLE);
                }
            }
        });

    }

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

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

    /**
     * ?
     */
    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // ?id
            String msgId = intent.getStringExtra("msgid");

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

            /***********???????*********** /
            UserDao dao = new UserDao(MainActivity.this);
            User userget = dao.getUser(toChatUsername);  
            String nickname_tmp = "";
            String headurl_tmp = "";
            //?
            ///if(CommonUtils.isNullOrEmpty(userget.toString())){
                //???id?
               if(CommonUtils.isNullOrEmpty(userget.getUsername())&&
              CommonUtils.isNullOrEmpty(userget.getHeaderurl())&&
                 CommonUtils.isNullOrEmpty(userget.getNick())){
                
                  String httpUrl = Constant.BASE_URL
                 + Constant.USER_URL_C + "user="
                 + toChatUsername;
                  // httpRequest
                  HttpGet httpRequest = new HttpGet(httpUrl);
                      
                  try {
              // ?HttpClient
              HttpClient httpclient = new DefaultHttpClient();
              // HttpClient?HttpResponse
              HttpResponse httpResponse = httpclient
                    .execute(httpRequest);
              // ?
              if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                 // ?
                 String strResult = EntityUtils.toString(httpResponse.getEntity());
                 if(!CommonUtils.isNullOrEmpty(strResult)){
                    Map<String, Object> lm = JsonToMapList.getMap(strResult);
                    if(lm.get("status").toString() != null && lm.get("status").toString().equals("yes")){
                       if(!CommonUtils.isNullOrEmpty(lm.get("result"))){ 
                          Map<String, Object> result = JsonToMapList.getMap(lm.get("result").toString());
                          nickname_tmp = result.get("nickname").toString();
                          headurl_tmp = result.get("headurl").toString(); 
                          Log.d("NotifyListener","nickname_tmp and headurl_tmp "+nickname_tmp+" "+headurl_tmp);
                               
                       } 
                    } 
                 } 
                     
                 if(!CommonUtils.isNullOrEmpty(nickname_tmp)&&!CommonUtils.isNullOrEmpty(headurl_tmp)){
                     User user_temp =  new User();
                     user_temp.setUsername(toChatUsername);
                     user_temp.setNick(nickname_tmp);
                     user_temp.setHeaderurl(headurl_tmp);
                     //??
                    if(DemoApplication.getInstance().getContactList().containsKey(toChatUsername)){
                       dao.saveContact(user_temp);
                    }else{
                       dao.saveContact_m(user_temp);
                    }
                     Log.d("NotifyListener","saveContact_m have");
                  } 
              }  
                  
                  } catch (ClientProtocolException e) {
              Log.d("application", e.getMessage().toString());
                  } catch (IOException e) {
              Log.d("application", e.getMessage().toString());
                  } catch (Exception e) {
              Log.d("application", e.getMessage().toString());
                  }
               }
            //}
            /***********???????***********/
            /****************************************??******************************************/

            final UserDao userdao = new UserDao(context);
            final User local_user = userdao.getUser(toChatUsername);
            //?
            if (CommonUtils.isNullOrEmpty(local_user.toString())) { //new ?null
                RequestParams params = new RequestParams();
                params.add("user", toChatUsername);
                HttpRestClient.get(Constant.USER_URL_C, params, new BaseJsonHttpResponseHandler() {
                    //private String nickname;
                    //private String headurl;
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse,
                            Object response) {
                        // TODO Auto-generated method stub
                        Log.d("rawJsonResponse", rawJsonResponse);
                        if (CommonUtils.isNullOrEmpty(rawJsonResponse)) {
                            nickname = "";
                            headurl = "";
                        }
                        Map<String, Object> lm = JsonToMapList.getMap(rawJsonResponse);
                        if (lm.get("status").toString() != null && lm.get("status").toString().equals("yes")) {
                            if (!CommonUtils.isNullOrEmpty(lm.get("result"))) {
                                Map<String, Object> result = JsonToMapList.getMap(lm.get("result").toString());
                                nickname = result.get("nickname").toString();
                                headurl = result.get("headurl").toString();
                                local_user.setUsername(toChatUsername);
                                local_user.setNick(nickname);
                                local_user.setHeaderurl(headurl);
                                userdao.saveContact_m(local_user);
                                /*******************0901**********************/
                                //if (currentTabIndex == 2) {
                                // ??????
                                if (chatHistoryFragment != null) {
                                    chatHistoryFragment.refresh();
                                }
                                //}
                                /*********************0901********************/
                            } else {
                                nickname = "";
                                headurl = "";
                            }
                        } else {
                            nickname = "";
                            headurl = "";
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData,
                            Object errorResponse) {
                        // TODO Auto-generated method stub
                        nickname = "";
                        headurl = "";
                    }

                    @Override
                    protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                        // TODO Auto-generated method stub
                        return null;
                    }

                });
            } else {//??
                Log.d("local_user", "" + local_user.toString());
                nickname = "";
                headurl = "";
            }
            /****************************************??*****************************************/

            // bottom bar?
            updateUnreadLabel();
            if (currentTabIndex == CHATHISTORYFRAGMENT) {
                // ??????
                if (chatHistoryFragment != null) {
                    chatHistoryFragment.refresh();
                }
            }
            Log.d("log", "mainactivity NewMessageBroadcastReceiver==================");
            // ?ChatActivity
            abortBroadcast();
        }
    }

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

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

    /**
     * ?BroadcastReceiver
     * sdk ????clientreceiverUI ???
     * UI ????
     */
    private BroadcastReceiver offlineMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String[] users = intent.getStringArrayExtra("fromuser");
            String[] groups = intent.getStringArrayExtra("fromgroup");
            if (users != null) {
                for (String user : users) {
                    Log.d("log", "user?" + user);

                    if (DemoApplication.getInstance().getContactList().containsKey(user)) {
                        get_add_info(user, true);
                    } else {
                        get_add_info(user, false);
                    }

                }
            }
            if (groups != null) {
                for (String group : groups) {
                    Log.d("log", "group?" + group);
                }
            }
            abortBroadcast();
        }

        /*********************************************************************************************/
        private void get_add_info(final String toChatUsername, final boolean is_fran) {
            new Thread(new Runnable() {
                public void run() {
                    // TODO Auto-generated method stub
                    /****************************************??******************************************/
                    //final String toChatUsername = intent.getStringExtra("from"); 
                    final UserDao userdao = new UserDao(MainActivity_0903.this);
                    final User local_user = userdao.getUser(toChatUsername);
                    //?
                    if (CommonUtils.isNullOrEmpty(local_user.toString())) {
                        RequestParams params = new RequestParams();
                        params.add("user", toChatUsername);
                        HttpRestClient.get(Constant.USER_URL_C, params, new BaseJsonHttpResponseHandler() {

                            @Override
                            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse,
                                    Object response) {
                                // TODO Auto-generated method stub
                                Log.d("rawJsonResponse", rawJsonResponse);
                                if (CommonUtils.isNullOrEmpty(rawJsonResponse)) {
                                    nickname = "";
                                    headurl = "";
                                }
                                Map<String, Object> lm = JsonToMapList.getMap(rawJsonResponse);
                                if (lm.get("status").toString() != null
                                        && lm.get("status").toString().equals("yes")) {
                                    if (!CommonUtils.isNullOrEmpty(lm.get("result"))) {
                                        Map<String, Object> result = JsonToMapList
                                                .getMap(lm.get("result").toString());
                                        nickname = result.get("nickname").toString();
                                        headurl = result.get("headurl").toString();
                                        local_user.setUsername(toChatUsername);
                                        local_user.setNick(nickname);
                                        local_user.setHeaderurl(headurl);
                                        if (is_fran) {
                                            userdao.saveContact(local_user);
                                        } else {
                                            userdao.saveContact_m(local_user);
                                        }
                                        /*********************0902********************** /
                                        if (currentTabIndex != CHATHISTORYFRAGMENT) {
                                           FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
                                           trx.hide(fragments[currentTabIndex]);
                                           if (!fragments[CHATHISTORYFRAGMENT].isAdded()) {
                                              trx.add(R.id.fragment_container, fragments[CHATHISTORYFRAGMENT]);
                                           }
                                           trx.show(fragments[CHATHISTORYFRAGMENT]).commit();
                                        }
                                        /*****************0901****************** /
                                        //if (currentTabIndex == 2) {
                                           // ??????
                                           if (chatHistoryFragment != null) {
                                              chatHistoryFragment.refresh();
                                           }
                                        //}
                                        /******************0901end*****************/
                                    } else {
                                        nickname = "";
                                        headurl = "";
                                    }
                                } else {
                                    nickname = "";
                                    headurl = "";
                                }
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, Throwable throwable,
                                    String rawJsonData, Object errorResponse) {
                                // TODO Auto-generated method stub
                                nickname = "";
                                headurl = "";
                            }

                            @Override
                            protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                                // TODO Auto-generated method stub
                                return null;
                            }

                        });
                    } else {//??
                        Log.d("local_user", "" + local_user.toString());
                        nickname = "";
                        headurl = "";
                    }
                    /****************************************??*****************************************/
                }
            }).start();
        }
    };

    private InviteMessgeDao inviteMessgeDao;
    private UserDao userDao;

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

        @Override
        public void onContactAdded(List<String> usernameList) {
            // ??
            Map<String, User> localUsers = DemoApplication.getInstance().getContactList();
            Map<String, User> toAddUsers = new HashMap<String, User>();
            for (String username : usernameList) {
                User user = setUserHead(username);
                // bug??added
                if (!localUsers.containsKey(username)) {
                    get_add_info(username, true);
                    //userDao.saveContact(user); ??
                }
                toAddUsers.put(username, user);
            }
            localUsers.putAll(toAddUsers);
            // ui
            if (currentTabIndex == CONTACTLISTFRAGMENT)
                contactListFragment.refresh();

        }

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

                }
            });
            // ui
            if (currentTabIndex == CONTACTLISTFRAGMENT)
                contactListFragment.refresh();

        }

        @Override
        public void onContactInvited(String username, String reason) {
            // ???(???)???????????
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getGroupId() == null && inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }
            //??
            get_add_info(username, false);
            // ?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;
                }
            }
            //??
            //get_add_info(username);
            // ?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

        }

        public void get_add_info(final String toChatUsername, final boolean is_fran) {
            new Thread(new Runnable() {
                public void run() {
                    /****************************************??******************************************/
                    //final String toChatUsername = intent.getStringExtra("from"); 
                    final UserDao userdao = new UserDao(MainActivity_0903.this);
                    final User local_user = userdao.getUser(toChatUsername);
                    //?
                    if (CommonUtils.isNullOrEmpty(local_user.toString())) {
                        RequestParams params = new RequestParams();
                        params.add("user", toChatUsername);
                        HttpRestClient.get(Constant.USER_URL_C, params, new BaseJsonHttpResponseHandler() {

                            @Override
                            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse,
                                    Object response) {
                                // TODO Auto-generated method stub
                                Log.d("rawJsonResponse", rawJsonResponse);
                                if (CommonUtils.isNullOrEmpty(rawJsonResponse)) {
                                    nickname = "";
                                    headurl = "";
                                }
                                Map<String, Object> lm = JsonToMapList.getMap(rawJsonResponse);
                                if (lm.get("status").toString() != null
                                        && lm.get("status").toString().equals("yes")) {
                                    if (!CommonUtils.isNullOrEmpty(lm.get("result"))) {
                                        Map<String, Object> result = JsonToMapList
                                                .getMap(lm.get("result").toString());
                                        nickname = result.get("nickname").toString();
                                        headurl = result.get("headurl").toString();
                                        local_user.setUsername(toChatUsername);
                                        local_user.setNick(nickname);
                                        local_user.setHeaderurl(headurl);
                                        if (is_fran) {
                                            userdao.saveContact(local_user);
                                        } else {
                                            userdao.saveContact_m(local_user);
                                        }
                                    } else {
                                        nickname = "";
                                        headurl = "";
                                    }
                                } else {
                                    nickname = "";
                                    headurl = "";
                                }
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, Throwable throwable,
                                    String rawJsonData, Object errorResponse) {
                                // TODO Auto-generated method stub
                                nickname = "";
                                headurl = "";
                            }

                            @Override
                            protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                                // TODO Auto-generated method stub
                                return null;
                            }

                        });
                    } else {//??
                        Log.d("local_user", "" + local_user.toString());
                        nickname = "";
                        headurl = "";
                    }
                    /****************************************??*****************************************/
                }
            }).start();
        }

    }

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

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

    /**
     * ?msg
     * @param msg
     */
    private void saveInviteMsg(InviteMessage msg) {
        // ?msg
        inviteMessgeDao.saveMessage(msg);
        // 1
        User user = DemoApplication.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME);
        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 ConnectionListener {

        @Override
        public void onConnected() {

            if (fragments[2].isAdded()) {//??
                chatHistoryFragment.errorItem.setVisibility(View.GONE);
            }
            //chatHistoryFragment.errorItem.setVisibility(View.GONE);
        }

        @Override
        public void onDisConnected(String errorString) {
            if (errorString != null && errorString.contains("conflict")) {
                // ??dialog
                showConflictDialog();
            } else {
                //if (chatHistoryFragment != null) {
                if (fragments[2].isAdded()) {//?? 
                    chatHistoryFragment.errorItem.setVisibility(View.VISIBLE);
                    if (NetUtils.hasNetwork(MainActivity_0903.this))
                        chatHistoryFragment.errorText.setText("???");
                    else
                        chatHistoryFragment.errorText.setText("???");
                }
                //chatHistoryFragment.errorItem.setVisibility(View.VISIBLE);
                //chatHistoryFragment.errorText.setText("???");
            }
        }

        @Override
        public void onReConnected() {
            //if (chatHistoryFragment != null) {
            if (fragments[2].isAdded()) {//?? 
                chatHistoryFragment.errorItem.setVisibility(View.GONE);
            }
            //chatHistoryFragment.errorItem.setVisibility(View.GONE);
        }

        @Override
        public void onReConnecting() {
        }

        @Override
        public void onConnecting(String progress) {
        }

    }

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

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

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

            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    // ui
                    if (currentTabIndex == CHATHISTORYFRAGMENT)
                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainActivity_0903.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

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

        }

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

        }

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

                }
            });
        }

        @Override
        public void onGroupDestroy(String groupId, String groupName) {
            // 
            // ??,demo?
            // ui
            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    if (currentTabIndex == CHATHISTORYFRAGMENT)
                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainActivity_0903.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

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

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

            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    // ui
                    if (currentTabIndex == CHATHISTORYFRAGMENT)
                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainActivity_0903.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });
        }

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

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isConflict) {
            updateUnreadLabel();
            updateUnreadAddressLable();
            EMChatManager.getInstance().activityResumed();
        }

    }

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

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

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

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

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

        }

    }

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

    @Override
    public void onMySelected(int i) {
        // TODO Auto-generated method stub
        change_f(i);//?fragment
    }

    @Override
    public void onrefresh(String adr) {
        // TODO Auto-generated method stub
        //change_f(i);//?fragment
        if (fragments[4].isAdded()) {//??
            settingFragment.tv_user_zainadongtai.setText(adr);
        }
        //(settingFragment)findViewById(R.id.tv_user_zainadongtai);
    }

    public void showFloatingButton() {
        //  
        this.startService(new Intent(this, com.ccxt.whl.service.FloatService.class));
        // new TableShowView(this).fun(); ?activity?   
        // activity??[????] ?view  
        // ????tableviewwindowManager
        //          finish();
    }
}