Java tutorial
/** * 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.grass.caishi.cc.activity; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.apache.http.Header; import org.json.JSONException; import org.json.JSONObject; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.easemob.EMCallBack; import com.easemob.EMConnectionListener; import com.easemob.EMError; import com.easemob.EMEventListener; import com.easemob.EMGroupChangeListener; import com.easemob.EMNotifierEvent; import com.easemob.EMValueCallBack; 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.EMConversation.EMConversationType; import com.easemob.chat.EMMessage.ChatType; import com.easemob.chat.EMMessage.Type; import com.easemob.chat.TextMessageBody; import com.easemob.exceptions.EaseMobException; import com.easemob.util.EMLog; import com.easemob.util.HanziToPinyin; import com.easemob.util.NetUtils; import com.grass.caishi.cc.Constant; import com.grass.caishi.cc.DemoHXSDKHelper; import com.grass.caishi.cc.MyApplication; import com.grass.caishi.cc.R; import com.grass.caishi.cc.db.InviteMessgeDao; import com.grass.caishi.cc.db.UserDao; import com.grass.caishi.cc.domain.InviteMessage; import com.grass.caishi.cc.domain.InviteMessage.InviteMesageStatus; import com.grass.caishi.cc.domain.User; import com.grass.caishi.cc.frag.ChatMessageFragment; import com.grass.caishi.cc.frag.FriendsListFragment; import com.grass.caishi.cc.frag.SelectCityFragment; import com.grass.caishi.cc.frag.SettingsFragment; import com.grass.caishi.cc.frag.SelectMainFragment; import com.grass.caishi.cc.model.HXSDKHelper; import com.grass.caishi.cc.utils.CommonUtils; import com.grass.caishi.cc.utils.HttpRestClient; import com.grass.caishi.cc.utils.JsonToMapList; import com.grass.caishi.cc.utils.MyLogger; import com.grass.caishi.cc.utils.PreferenceUtils; import com.grass.caishi.cc.utils.UpdateDialog; import com.grass.caishi.cc.view.MyUpdataInfoView; import com.grass.caishi.net.UpLoadImage; import com.grass.view.MyDialog; import com.grass.view.MyDialog.OnSweetClickListener; import com.loopj.android.http.RequestParams; import com.loopj.android.http.TextHttpResponseHandler; import com.nostra13.universalimageloader.utils.StorageUtils; public class MainActivity extends BaseActivity implements EMEventListener { // , CheckUpdateListener,PostChoiceListener{ protected static final String TAG = "MainActivity"; // public static b // ?textview private TextView unreadLabel; // textview private TextView unreadAddressLable; // ?textview private TextView unreadQuanLabel; private boolean canGetQuan = false; private long stopTime = 0; private Button[] mTabs; private SelectCityFragment selectCityFrament;// ? private SelectMainFragment selectMainFrament;// ? // private ChatHistoryFragment chatHistoryFragment; private ChatMessageFragment chatMessageFragment;// ?? private FriendsListFragment friendsListFragment;// ?? private SettingsFragment settingFragment;// ? private Fragment[] fragments; private int index; // private RelativeLayout[] tab_containers; // ?fragmentindex private int currentTabIndex; // private NewMessageBroadcastReceiver msgReceiver; // ? public boolean isConflict = false; // ? public boolean isCurrentAccountRemoved = false; // private String nickname; // private String logo; /*** loadcontact ****/ // private String nickname_tmp = ""; // private String logo_tmp = ""; private final static int INDEX_MESSAGE_MAIN = 0; private final static int INDEX_SELECTED_MAIN = 1; private final static int INDEX_NOTHING_MAIN = 2; private final static int INDEX_FRIENDS_MAIN = 3; private final static int INDEX_SETTING_MAIN = 4; public final static int MAIN_MESSAGE_LOGIN_OUT = 404; public final static int MAIN_MESSAGE_SYSTEM_OUT = 444; // ???? private UpdateDialog utestUpdate; // private CheckUpdateListener mCheckUpdateResponse; // private PostChoiceListener mPostUpdateChoiceListener; private static MyLogger Log = MyLogger.yLog(); private boolean isConflictDialogShow; private boolean isAccountRemovedDialogShow; private InviteMessgeDao inviteMessgeDao; private UserDao userDao; private Button[] menuBtn; private int add_code = 0; public boolean hasNewNotice = false; public boolean hasNewNotice2 = false; public boolean hasNewQaun = false; public boolean getNewQuan() { return hasNewQaun; } public void setNewQuan() { hasNewQaun = false; } public boolean getNewNotice() { return hasNewNotice; } public void setNewNotice() { hasNewNotice = false; } public boolean getNewNotice2() { return hasNewNotice2; } public void setNewNotice2() { hasNewNotice2 = false; } public void setAddCode(int addcode) { this.add_code = addcode; } public int getAddCode() { return add_code; } /** * ?? */ public boolean getCurrentAccountRemoved() { return isCurrentAccountRemoved; } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { hideNavigationBar(); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { super.onKeyUp(keyCode, event); if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { this.hideNavigationBar(); } return false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) { // ??home???appcrash // fragment?? MyApplication.getInstance().logout(null); finish(); startActivity(new Intent(this, LoginActivity.class)); return; } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) { // T??home???appcrash // fragment?? finish(); startActivity(new Intent(this, LoginActivity.class)); return; } hideNavigationBar(); setContentView(R.layout.activity_main); initView(); try { add_code = Integer.valueOf(PreferenceUtils.getInstance(this).getSettingUserCityCode()); } catch (Exception e) { // } if (getIntent().getBooleanExtra("conflict", false) && !isConflictDialogShow) { showConflictDialog(); } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) { showAccountRemovedDialog(); } inviteMessgeDao = new InviteMessgeDao(this); userDao = new UserDao(this); selectCityFrament = new SelectCityFragment(); selectMainFrament = new SelectMainFragment(); // fragment??? // chatHistoryFragment = new ChatHistoryFragment(); // ?fragment chatMessageFragment = new ChatMessageFragment(); friendsListFragment = new FriendsListFragment(); settingFragment = new SettingsFragment(); fragments = new Fragment[] { chatMessageFragment, selectCityFrament, selectMainFrament, friendsListFragment, settingFragment }; getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, chatMessageFragment) .add(R.id.fragment_container, friendsListFragment).hide(friendsListFragment) .show(chatMessageFragment).commit(); init(); // refreshFriends(); mainLoad(); new Thread(new Runnable() { @Override public void run() { // deleteAllFiles(StorageUtils.getOwnCacheDirectory(MainActivity.this, Constant.CACHE_DIR_IMAGE)); } }).start(); if (!getIntent().getBooleanExtra("login", false)) { refreshFriends(); } findViewById(R.id.btn_main_circle_community).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO 21 startActivity(new Intent(MainActivity.this, TimeListActivity.class)); } }); } public void Update(Map<String, Object> data) { if (data != null) { int code = Integer.valueOf(data.get("code").toString()); PackageManager pm = getPackageManager();// context?Activity PackageInfo pi; try { pi = pm.getPackageInfo(getPackageName(), 0); if (code > pi.versionCode) { String name = data.get("name").toString(); String text = data.get("text").toString(); String url = data.get("url").toString(); String time = data.get("time").toString(); Toast.makeText(this, "" + name, Toast.LENGTH_SHORT).show(); MyUpdataInfoView myup = new MyUpdataInfoView(this); if (this.getParent() != null) myup = new MyUpdataInfoView(this.getParent()); myup.setTitle(name); myup.setTime(time); myup.setInfo(text); if (code - pi.versionCode > 9) { myup.setMustUp(true); } myup.setDownloadUrl(url); myup.show(MainActivity.this.findViewById(R.id.fragment_container)); } } catch (NameNotFoundException e) { // e.printStackTrace(); } } } private void deleteAllFiles(File root) { File files[] = root.listFiles(); if (files != null) for (File f : files) { if (f.isDirectory()) { // ? deleteAllFiles(f); } else { if (f.exists()) { // ? try { f.delete(); } catch (Exception e) { } } } } } public void mainLoad() { dialog.setMessage("??..."); dialog.show(); RequestParams params = new RequestParams(); // String uid = PreferenceUtils.getInstance(this).getSettingUserID(); params.put("type", "main"); HttpRestClient.post(Constant.GET_USER_INFO_FROM_ID, params, mainTextPonsehandler); } private TextHttpResponseHandler mainTextPonsehandler = new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { // dialog.dismiss(); System.out.println(responseString); if (CommonUtils.isNullOrEmpty(responseString)) { return; } Map<String, Object> lm = JsonToMapList.getMap(responseString); if (lm != null && lm.get("ok") != null && lm.get("ok").toString().equals("1")) { Map<String, Object> result = JsonToMapList.getMap(lm.get("data").toString()); Map<String, Object> user = JsonToMapList.getMap(result.get("user").toString()); // Map<String, Object> main = JsonToMapList.getMap(result.get("match").toString()); Map<String, Object> bg = JsonToMapList.getMap(result.get("bg").toString()); System.out.println(result.get("bg").toString()); Map<String, Object> app = null; if (!CommonUtils.isNullOrEmpty(result.get("app"))) { app = JsonToMapList.getMap(result.get("app").toString()); } /**** ****/ if (!CommonUtils.isNullOrEmpty(user) && !CommonUtils.isNullOrEmpty(user.get("user_id"))) { PreferenceUtils.getInstance(MainActivity.this).setSettingUserID(user.get("user_id").toString()); // String name = result.get("user_nick").toString(); PreferenceUtils.getInstance(MainActivity.this) .setSettingUserName(user.get("user_name").toString()); PreferenceUtils.getInstance(MainActivity.this) .setSettingUserLogo(user.get("user_logo").toString()); PreferenceUtils.getInstance(MainActivity.this) .setSettingUserNick(user.get("user_nick").toString()); PreferenceUtils.getInstance(MainActivity.this) .setSettingUserSex(Integer.valueOf(user.get("user_sex").toString())); PreferenceUtils.getInstance(MainActivity.this) .setSettingUserVote(Integer.valueOf(user.get("user_vote").toString())); PreferenceUtils.getInstance(MainActivity.this).setSettingUserBG(user.get("user_bg").toString()); PreferenceUtils.getInstance(MainActivity.this) .setSettingUserCity(user.get("user_add_name").toString()); PreferenceUtils.getInstance(MainActivity.this) .setSettingUserCityCode(user.get("user_add_code").toString()); PreferenceUtils.getInstance(MainActivity.this).setSettingQuanBG(user.get("quan_bg").toString()); PreferenceUtils.getInstance(MainActivity.this) .setSettingUserAge(Integer.valueOf(user.get("user_age").toString())); if (CommonUtils.isNullOrEmpty(user.get("user_money"))) { PreferenceUtils.getInstance(getBaseContext()).setSettingUserMoney("0.00"); } else { PreferenceUtils.getInstance(getBaseContext()) .setSettingUserMoney(user.get("user_money").toString()); } } else { logout(); return; } // PreferenceUtils.getInstance(getActivity()).setSettingu(result.get("quan_bg").toString()); /* * ??? progressShow = false; pd.dismiss(); */ // if (main != null) { // if (!CommonUtils.isNullOrEmpty(main.get("nv"))) // PreferenceUtils.getInstance(MainActivity.this).setMainMatchNnLogo(main.get("nv").toString()); // if (!CommonUtils.isNullOrEmpty(main.get("nan"))) // PreferenceUtils.getInstance(MainActivity.this).setMainMatchNanLogo(main.get("nan").toString()); // // selectCityFrament.refreshView(); // } else { // PreferenceUtils.getInstance(MainActivity.this).setMainMatchNnLogo(null); // PreferenceUtils.getInstance(MainActivity.this).setMainMatchNanLogo(null); // } donBlackground(bg); settingFragment.InitData(false); Update(app); } // dialog.dismiss(); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { // dialog.dismiss(); } }; @SuppressWarnings("unchecked") public void donBlackground(Map<String, Object> map) { new AsyncTask<Map<String, Object>, Void, Void>() { @Override protected Void doInBackground(Map<String, Object>... params) { // try { new UpLoadImage().download(getApplicationContext(), params[0]); } catch (Exception e) { // e.printStackTrace(); } return null; } }.execute(map); } /** * ?? */ private TextHttpResponseHandler textresponsehandler = new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { // if (CommonUtils.isNullOrEmpty(responseString)) { return; } Map<String, Object> ml = JsonToMapList.getMap(responseString); if (!CommonUtils.isNullOrEmpty(ml.get("data")) && ml.get("ok").toString().equals("1")) { List<Map<String, Object>> li = JsonToMapList.getList(ml.get("data").toString()); Map<String, User> userlist = new HashMap<String, User>(); for (int i = 0; i < li.size(); i++) { Map<String, Object> map = li.get(i); String user_name = map.get("user_name").toString(); User user = new User(); user.setUsername(user_name); if (!CommonUtils.isNullOrEmpty(map.get("user_nick"))) user.setNick(map.get("user_nick").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_id"))) user.setUser_id(Integer.valueOf(map.get("user_id").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_logo"))) user.setLogo(map.get("user_logo").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_add_code"))) user.setCity_code(Integer.valueOf(map.get("user_add_code").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_add_name"))) user.setCity(map.get("user_add_name").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_sex"))) user.setSex(Integer.valueOf(map.get("user_sex").toString())); if (!CommonUtils.isNullOrEmpty(map.get("quan_bg"))) user.setQuan_bg(map.get("quan_bg").toString()); user.setIs_friend(true); setUserHearder(user_name, user); userlist.put(user_name, user); } User newFriends = new User(); newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME); newFriends.setNick(""); newFriends.setHeader(""); newFriends.setIs_friend(true); userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends); // "?" User kefu = new User(); kefu.setUsername(Constant.KEFU); kefu.setNick("??"); kefu.setLogo(""); kefu.setHeader(""); kefu.setIs_friend(true); userlist.put(Constant.KEFU, kefu); MyApplication.getInstance().setContactList(userlist); List<User> liusers = new ArrayList<User>(userlist.values()); userDao.saveContactList(liusers, true); friendsListFragment.refresh(); friendsListFragment.setRefreshDone(); chatMessageFragment.refresh(); } // if (currentTabIndex == INDEX_FRIENDS_MAIN) } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { // Toast.makeText(MainActivity.this, "?", Toast.LENGTH_SHORT).show(); friendsListFragment.setRefreshDone(); } }; public void refreshFriends() { new Thread(new Runnable() { @Override public void run() { // List<String> usernames; try { usernames = EMChatManager.getInstance().getContactUserNames(); if (usernames == null || usernames.size() == 0) { Map<String, User> userlist = new HashMap<String, User>(); User newFriends = new User(); newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME); newFriends.setNick(""); newFriends.setHeader(""); newFriends.setIs_friend(true); userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends); // "?" User kefu = new User(); kefu.setUsername(Constant.KEFU); kefu.setNick("??"); kefu.setLogo(""); kefu.setHeader(""); kefu.setIs_friend(true); userlist.put(Constant.KEFU, kefu); MyApplication.getInstance().setContactList(userlist); List<User> liusers = new ArrayList<User>(userlist.values()); userDao.saveContactList(liusers, true); Thread.sleep(500); runOnUiThread(new Runnable() { public void run() { friendsListFragment.refresh(); friendsListFragment.setRefreshDone(); } }); } else { String users = ""; for (String username : usernames) { users = users + username + "#"; } RequestParams params = new RequestParams(); params.put("users", users); HttpRestClient.post(Constant.GET_USERS_LIST_INFO, params, textresponsehandler); } } catch (EaseMobException | InterruptedException e) { // e.printStackTrace(); } } }).start(); } private MyConnectionListener connectionListener = null; private MyGroupChangeListener groupChangeListener = null; private void init() { // setContactListener??? EMContactManager.getInstance().setContactListener(new MyContactListener()); // ??listener connectionListener = new MyConnectionListener(); EMChatManager.getInstance().addConnectionListener(connectionListener); groupChangeListener = new MyGroupChangeListener(); // ?listener EMGroupManager.getInstance().addGroupChangeListener(groupChangeListener); // // registerInternalDebugReceiver(); } /*** * ??listener * */ public class MyContactListener implements EMContactListener { @Override public void onContactAdded(List<String> usernameList) { // // ?? // System.out.println("fffffffffffffffffffffffffffffffffffffff"); // String users = ""; // Map<String, User> localUsers = MyApplication.getInstance().getContactList(false); // // Map<String, User> toAddUsers = new HashMap<String, User>(); // for (String username : usernameList) { // User user = setUserHead(username); // // ??added // if (!localUsers.containsKey(username)) { // userDao.saveContact(user); // users = users + username + "#"; // } // // toAddUsers.put(username, user); // } // // localUsers.putAll(toAddUsers); // // ui // if (currentTabIndex == INDEX_FRIENDS_MAIN) // friendsListFragment.refresh(true); // if (users.length() > 2) { // RequestParams params = new RequestParams(); // params.put("users", users); // HttpRestClient.post(Constant.GET_USERS_LIST_INFO, params, new TextHttpResponseHandler() { // @Override // public void onSuccess(int statusCode, Header[] headers, String responseString) { // // // if (CommonUtils.isNullOrEmpty(responseString)) { // return; // } // // Map<String, Object> ml = JsonToMapList.getMap(responseString); // if (!CommonUtils.isNullOrEmpty(ml.get("data")) && ml.get("ok").toString().equals("1")) { // List<Map<String, Object>> li = JsonToMapList.getList(ml.get("data").toString()); // Map<String, User> userlist = new HashMap<String, User>(); // for (int i = 0; i < li.size(); i++) { // Map<String, Object> map = li.get(i); // String user_name = map.get("user_name").toString(); // User user = new User(); // user.setUsername(user_name); // if (!CommonUtils.isNullOrEmpty(map.get("user_nick"))) // user.setNick(map.get("user_nick").toString()); // if (!CommonUtils.isNullOrEmpty(map.get("user_id"))) // user.setUser_id(Integer.valueOf(map.get("user_id").toString())); // if (!CommonUtils.isNullOrEmpty(map.get("user_logo"))) // user.setLogo(map.get("user_logo").toString()); // if (!CommonUtils.isNullOrEmpty(map.get("user_add_code"))) // user.setCity_code(Integer.valueOf(map.get("user_add_code").toString())); // if (!CommonUtils.isNullOrEmpty(map.get("user_add_name"))) // user.setCity(map.get("user_add_name").toString()); // if (!CommonUtils.isNullOrEmpty(map.get("user_sex"))) // user.setSex(Integer.valueOf(map.get("user_sex").toString())); // if (!CommonUtils.isNullOrEmpty(map.get("quan_bg"))) // user.setQuan_bg(map.get("quan_bg").toString()); // user.setIs_friend(true); // setUserHearder(user_name, user); // userlist.put(user_name, user); // } // MyApplication.getInstance().addContactList(userlist); // List<User> liusers = new ArrayList<User>(userlist.values()); // userDao.saveContactList(liusers, false); // // friendsListFragment.refresh(true); // friendsListFragment.setRefreshDone(); // chatMessageFragment.refresh(); // } // // if (currentTabIndex == INDEX_FRIENDS_MAIN) // // } // // @Override // public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { // // // // } // }); // } } @Override public void onContactDeleted(final List<String> usernameList) { // Map<String, User> localUsers = MyApplication.getInstance().getContactList(false); for (String username : usernameList) { localUsers.remove(username); userDao.deleteContact(username); inviteMessgeDao.deleteMessage(username); } runOnUiThread(new Runnable() { public void run() { // ?? String st10 = getResources().getString(R.string.have_you_removed); if (ChatActivity.activityInstance != null && usernameList.contains(ChatActivity.activityInstance.getToChatUsername())) { Toast.makeText(MainActivity.this, ChatActivity.activityInstance.getToChatUsername() + st10, 1).show(); ChatActivity.activityInstance.finish(); } updateUnreadLabel(); // ui friendsListFragment.refresh(); chatMessageFragment.refresh(); } }); } @Override public void onContactInvited(final String username, final String reason) { // ???(???)??????????? List<InviteMessage> msgs = inviteMessgeDao.getMessagesList(); for (InviteMessage inviteMessage : msgs) { if (inviteMessage.getGroupId() == null && inviteMessage.getFrom().equals(username)) { inviteMessgeDao.deleteMessage(username); } } if (MyApplication.getInstance().getVersionCode() > 45) { // ?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); } else { runOnUiThread(new Runnable() { public void run() { // inviteMessgeDao.saveMessage(msg); RequestParams params = new RequestParams(); params.put("users", username); HttpRestClient.post(Constant.GET_USERS_LIST_INFO, params, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { // if (CommonUtils.isNullOrEmpty(responseString)) { return; } Map<String, Object> ml = JsonToMapList.getMap(responseString); if (!CommonUtils.isNullOrEmpty(ml.get("data")) && ml.get("ok").toString().equals("1")) { Map<String, User> userlist = MyApplication.getInstance().getContactList(false); List<Map<String, Object>> li = JsonToMapList.getList(ml.get("data").toString()); Map<String, Object> map = li.get(0); String user_name = map.get("user_name").toString(); User user = userlist.get(user_name); if (user != null) { if (!CommonUtils.isNullOrEmpty(map.get("user_nick"))) user.setNick(map.get("user_nick").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_id"))) user.setUser_id(Integer.valueOf(map.get("user_id").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_logo"))) user.setLogo(map.get("user_logo").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_add_code"))) user.setCity_code(Integer.valueOf(map.get("user_add_code").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_add_name"))) user.setCity(map.get("user_add_name").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_sex"))) user.setSex(Integer.valueOf(map.get("user_sex").toString())); user.setIs_friend(false); setUserHearder(user_name, user); userDao.saveContact(user); } else { user = new User(); user.setUsername(user_name); if (!CommonUtils.isNullOrEmpty(map.get("user_nick"))) user.setNick(map.get("user_nick").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_id"))) user.setUser_id(Integer.valueOf(map.get("user_id").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_logo"))) user.setLogo(map.get("user_logo").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_add_code"))) user.setCity_code(Integer.valueOf(map.get("user_add_code").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_add_name"))) user.setCity(map.get("user_add_name").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_sex"))) user.setSex(Integer.valueOf(map.get("user_sex").toString())); user.setIs_friend(false); setUserHearder(user_name, user); userDao.saveContact(user); } // ?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 onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { // } }); } }); } } @Override public void onContactAgreed(final String username) { List<InviteMessage> msgs = inviteMessgeDao.getMessagesList(); for (InviteMessage inviteMessage : msgs) { if (inviteMessage.getFrom().equals(username)) { return; } } InviteMessage msg = new InviteMessage(); msg.setFrom(username); msg.setTime(System.currentTimeMillis()); // Log.d(TAG, username + "???"); msg.setStatus(InviteMesageStatus.BEAGREED); inviteMessgeDao.saveMessage(msg); // ?javabean runOnUiThread(new Runnable() { public void run() { // inviteMessgeDao.saveMessage(msg); RequestParams params = new RequestParams(); params.put("users", username); HttpRestClient.post(Constant.GET_USERS_LIST_INFO, params, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { // if (CommonUtils.isNullOrEmpty(responseString)) { return; } System.out.println(responseString); Map<String, Object> ml = JsonToMapList.getMap(responseString); if (!CommonUtils.isNullOrEmpty(ml.get("data")) && ml.get("ok").toString().equals("1")) { Map<String, User> userlist = MyApplication.getInstance().getContactList(false); List<Map<String, Object>> li = JsonToMapList.getList(ml.get("data").toString()); Map<String, Object> map = li.get(0); String user_name = map.get("user_name").toString(); User user = userlist.get(user_name); if (user != null) { if (!CommonUtils.isNullOrEmpty(map.get("user_nick"))) user.setNick(map.get("user_nick").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_id"))) user.setUser_id(Integer.valueOf(map.get("user_id").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_logo"))) user.setLogo(map.get("user_logo").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_add_code"))) user.setCity_code(Integer.valueOf(map.get("user_add_code").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_add_name"))) user.setCity(map.get("user_add_name").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_sex"))) user.setSex(Integer.valueOf(map.get("user_sex").toString())); user.setIs_friend(true); setUserHearder(user_name, user); userDao.saveContact(user); } else { user = new User(); user.setUsername(user_name); if (!CommonUtils.isNullOrEmpty(map.get("user_nick"))) user.setNick(map.get("user_nick").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_id"))) user.setUser_id(Integer.valueOf(map.get("user_id").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_logo"))) user.setLogo(map.get("user_logo").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_add_code"))) user.setCity_code(Integer.valueOf(map.get("user_add_code").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_add_name"))) user.setCity(map.get("user_add_name").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_sex"))) user.setSex(Integer.valueOf(map.get("user_sex").toString())); user.setIs_friend(true); setUserHearder(user_name, user); userDao.saveContact(user); } MyApplication.getInstance().setContactUser(user); InviteMessage msg = new InviteMessage(); msg.setFrom(username); msg.setTime(System.currentTimeMillis()); // Log.d(TAG, username + "???"); JSONObject job = new JSONObject(); try { job.put("nick", user.getNick()); job.put("logo", user.getLogo()); job.put("name", user.getUsername()); job.put("uid", user.getUser_id()); job.put("msg", user.getNick() + "???"); } catch (JSONException e) { // e.printStackTrace(); } msg.setReason(job.toString()); msg.setStatus(InviteMesageStatus.BEAGREED); notifyNewIviteMessage(msg); } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { // } }); } }); } @Override public void onContactRefused(String username) { // ???,demo // Log.d(username, username + "??"); } } static void asyncFetchGroupsFromServer() { HXSDKHelper.getInstance().asyncFetchGroupsFromServer(new EMCallBack() { @Override public void onSuccess() { HXSDKHelper.getInstance().noitifyGroupSyncListeners(true); if (HXSDKHelper.getInstance().isContactsSyncedWithServer()) { HXSDKHelper.getInstance().notifyForRecevingEvents(); } } @Override public void onError(int code, String message) { HXSDKHelper.getInstance().noitifyGroupSyncListeners(false); } @Override public void onProgress(int progress, String status) { } }); } void asyncFetchContactsFromServer() { HXSDKHelper.getInstance().asyncFetchContactsFromServer(new EMValueCallBack<List<String>>() { @Override public void onSuccess(final List<String> usernames) { runOnUiThread(new Runnable() { @Override public void run() { String users = ""; for (String username : usernames) { users = users + username + "#"; } RequestParams params = new RequestParams(); params.put("users", users); HttpRestClient.post(Constant.GET_USERS_LIST_INFO, params, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { // if (CommonUtils.isNullOrEmpty(responseString)) { return; } Map<String, Object> ml = JsonToMapList.getMap(responseString); if (!CommonUtils.isNullOrEmpty(ml.get("data")) && ml.get("ok").toString().equals("1")) { List<Map<String, Object>> li = JsonToMapList.getList(ml.get("data").toString()); Map<String, User> userlist = new HashMap<String, User>(); for (int i = 0; i < li.size(); i++) { Map<String, Object> map = li.get(i); String user_name = map.get("user_name").toString(); User user = new User(); user.setUsername(user_name); if (!CommonUtils.isNullOrEmpty(map.get("user_nick"))) user.setNick(map.get("user_nick").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_id"))) user.setUser_id(Integer.valueOf(map.get("user_id").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_logo"))) user.setLogo(map.get("user_logo").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_add_code"))) user.setCity_code(Integer.valueOf(map.get("user_add_code").toString())); if (!CommonUtils.isNullOrEmpty(map.get("user_add_name"))) user.setCity(map.get("user_add_name").toString()); if (!CommonUtils.isNullOrEmpty(map.get("user_sex"))) user.setSex(Integer.valueOf(map.get("user_sex").toString())); if (!CommonUtils.isNullOrEmpty(map.get("quan_bg"))) user.setQuan_bg(map.get("quan_bg").toString()); user.setIs_friend(true); setUserHearder(user_name, user); userlist.put(user_name, user); } User newFriends = new User(); newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME); newFriends.setNick(""); newFriends.setHeader(""); newFriends.setIs_friend(true); userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends); // "?" User kefu = new User(); kefu.setUsername(Constant.KEFU); kefu.setNick("??"); kefu.setLogo(""); kefu.setHeader(""); kefu.setIs_friend(true); userlist.put(Constant.KEFU, kefu); MyApplication.getInstance().setContactList(userlist); List<User> liusers = new ArrayList<User>(userlist.values()); Context context = HXSDKHelper.getInstance().getAppContext(); UserDao dao = new UserDao(context); dao.saveContactList(liusers, true); } // if (currentTabIndex == INDEX_FRIENDS_MAIN) } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { // } }); HXSDKHelper.getInstance().notifyContactsSyncListener(true); if (HXSDKHelper.getInstance().isGroupsSyncedWithServer()) { HXSDKHelper.getInstance().notifyForRecevingEvents(); } } }); } @Override public void onError(int error, String errorMsg) { HXSDKHelper.getInstance().notifyContactsSyncListener(false); } }); } static void asyncFetchBlackListFromServer() { HXSDKHelper.getInstance().asyncFetchBlackListFromServer(new EMValueCallBack<List<String>>() { @Override public void onSuccess(List<String> value) { EMContactManager.getInstance().saveBlackList(value); HXSDKHelper.getInstance().notifyBlackListSyncListener(true); } @Override public void onError(int error, String errorMsg) { HXSDKHelper.getInstance().notifyBlackListSyncListener(false); } }); } /** * ?listener * */ public class MyConnectionListener implements EMConnectionListener { @Override public void onConnected() { boolean groupSynced = HXSDKHelper.getInstance().isGroupsSyncedWithServer(); boolean contactSynced = HXSDKHelper.getInstance().isContactsSyncedWithServer(); // in case group and contact were already synced, we supposed to // notify sdk we are ready to receive the events if (groupSynced && contactSynced) { new Thread() { @Override public void run() { HXSDKHelper.getInstance().notifyForRecevingEvents(); } }.start(); } else { if (!groupSynced) { asyncFetchGroupsFromServer(); } if (!contactSynced) { asyncFetchContactsFromServer(); } if (!HXSDKHelper.getInstance().isBlackListSyncedWithServer()) { asyncFetchBlackListFromServer(); } } runOnUiThread(new Runnable() { @Override public void run() { if (chatMessageFragment.errorItem != null) chatMessageFragment.errorItem.setVisibility(View.GONE); } }); } @Override public void onDisconnected(final int error) { final String st1 = "????..."; final String st2 = "?"; runOnUiThread(new Runnable() { @Override public void run() { if (error == EMError.USER_REMOVED) { // ??? showAccountRemovedDialog(); } else if (error == EMError.CONNECTION_CONFLICT) { // ??dialog showConflictDialog(); } else { if (chatMessageFragment.errorItem != null) { chatMessageFragment.errorItem.setVisibility(View.VISIBLE); if (NetUtils.hasNetwork(MainActivity.this)) chatMessageFragment.errorText.setText(st1); else chatMessageFragment.errorText.setText(st2); } } } }); } } /** * MyGroupChangeListener */ public class MyGroupChangeListener implements EMGroupChangeListener { @Override public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) { boolean hasGroup = false; for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) { if (group.getGroupId().equals(groupId)) { hasGroup = true; break; } } if (!hasGroup) return; // String st3 = getResources().getString(R.string.Invite_you_to_join_a_group_chat); EMMessage msg = EMMessage.createReceiveMessage(Type.TXT); msg.setChatType(ChatType.GroupChat); msg.setFrom(inviter); msg.setTo(groupId); msg.setMsgId(UUID.randomUUID().toString()); msg.addBody(new TextMessageBody(inviter + " " + st3)); // ?? EMChatManager.getInstance().saveMessage(msg); // ??? HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg); runOnUiThread(new Runnable() { public void run() { updateUnreadLabel(); // ui if (currentTabIndex == INDEX_MESSAGE_MAIN) chatMessageFragment.refresh(); if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) { GroupsActivity.instance.onResume(); } } }); } @Override public void onInvitationAccpted(String groupId, String inviter, String reason) { } @Override public void onInvitationDeclined(String groupId, String invitee, String reason) { } @Override public void onUserRemoved(String groupId, String groupName) { // ??Tdemo? // ui runOnUiThread(new Runnable() { public void run() { try { updateUnreadLabel(); if (currentTabIndex == INDEX_MESSAGE_MAIN) chatMessageFragment.refresh(); 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) { // // ??,demo? // ui runOnUiThread(new Runnable() { public void run() { updateUnreadLabel(); if (currentTabIndex == INDEX_MESSAGE_MAIN) chatMessageFragment.refresh(); if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) { GroupsActivity.instance.onResume(); } } }); } @Override public void onApplicationReceived(String groupId, String groupName, String applyer, String reason) { // ?08-27 16:26:47.672: W/linker(6508): libeasemob_jni.so has // text relocations. This is wasting memory and prevents security // hardening. Please fix. InviteMessage msg = new InviteMessage(); msg.setFrom(applyer); msg.setTime(System.currentTimeMillis()); msg.setGroupId(groupId); msg.setGroupName(groupName); msg.setReason(reason); // Log.d(TAG, applyer + " ?" + groupName); msg.setStatus(InviteMesageStatus.BEAPPLYED); notifyNewIviteMessage(msg); } @Override public void onApplicationAccept(String groupId, String groupName, String accepter) { String st4 = getResources().getString(R.string.Agreed_to_your_group_chat_application); // ?? EMMessage msg = EMMessage.createReceiveMessage(Type.TXT); msg.setChatType(ChatType.GroupChat); msg.setFrom(accepter); msg.setTo(groupId); msg.setMsgId(UUID.randomUUID().toString()); msg.addBody(new TextMessageBody(accepter + " " + st4)); // ???? EMChatManager.getInstance().saveMessage(msg); // ??? HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg); runOnUiThread(new Runnable() { public void run() { updateUnreadLabel(); // ui if (currentTabIndex == INDEX_MESSAGE_MAIN) chatMessageFragment.refresh(); if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) { GroupsActivity.instance.onResume(); } } }); } @Override public void onApplicationDeclined(String groupId, String groupName, String decliner, String reason) { // ?demo } } // private MyDialog dialog; /** * ??dialog */ private void showConflictDialog() { isConflictDialogShow = true; MyApplication.getInstance().logout(null); String st = "???"; if (!MainActivity.this.isFinishing()) { // clear up global variables try { MyDialog dialog = new MyDialog(this); dialog.setTitleText(st); dialog.changeAlertType(MyDialog.ERROR_TYPE); dialog.setConfirmClickListener(new OnSweetClickListener() { @Override public void onClick(MyDialog sweetAlertDialog) { // sweetAlertDialog.dismiss(); finish(); startActivity(new Intent(MainActivity.this, LoginActivity.class)); } }); dialog.setCancelable(false); dialog.show(); isConflict = true; } catch (Exception e) { EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage()); } } } /** * ??dialog */ private void showAccountRemovedDialog() { isAccountRemovedDialogShow = true; MyApplication.getInstance().logout(null); String st5 = "???"; if (!MainActivity.this.isFinishing()) { // clear up global variables try { MyDialog dialog = new MyDialog(MainActivity.this); dialog.setTitleText(st5); dialog.setConfirmClickListener(new OnSweetClickListener() { @Override public void onClick(MyDialog sweetAlertDialog) { // sweetAlertDialog.dismiss(); finish(); startActivity(new Intent(MainActivity.this, LoginActivity.class)); } }); dialog.setCancelable(false); dialog.show(); isCurrentAccountRemoved = true; } catch (Exception e) { EMLog.e(TAG, "---------color userRemovedBuilder error" + e.getMessage()); } } } /** * hearder?header??ABCD...???? * * @param username * @param user */ private static void setUserHearder(String username, User user) { 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("#"); } } } /** * ? */ private void initView() { unreadLabel = (TextView) findViewById(R.id.unread_msg_number); unreadAddressLable = (TextView) findViewById(R.id.unread_address_number); unreadQuanLabel = (TextView) findViewById(R.id.unread_quan_number); mTabs = new Button[5]; mTabs[0] = (Button) findViewById(R.id.btn_main_message);// ? mTabs[1] = (Button) findViewById(R.id.btn_main_city);// mTabs[2] = (Button) findViewById(R.id.btn_main_quanguo);// mTabs[3] = (Button) findViewById(R.id.btn_main_friend);// ? mTabs[4] = (Button) findViewById(R.id.btn_main_setting);// // tab? mTabs[0].setSelected(true); mTabs[0].setTextColor(Color.parseColor("#0491FC")); } /** * button * * @param view */ public void onTabClicked(View view) { switch (view.getId()) { case R.id.btn_main_message: index = 0; break; case R.id.btn_main_city: index = 1; break; case R.id.btn_main_quanguo: index = 2; break; case R.id.btn_main_friend: index = 3; break; case R.id.btn_main_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(); if (fragments[index] == settingFragment) { settingFragment.InitData(false); } } mTabs[currentTabIndex].setSelected(false); mTabs[currentTabIndex].setTextColor(getResources().getColor(R.color.gray_normal)); // ?tab? mTabs[index].setSelected(true); mTabs[index].setTextColor(Color.parseColor("#0491FC")); currentTabIndex = index; } // /** // * ?fragment // * // * @param index // */ // public void change_f11111(int index) { // // 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; // // } /** * ???? * * @param msg */ private void notifyNewIviteMessage(InviteMessage msg) { saveInviteMsg(msg); // ??? HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(null); // bottom bar? updateUnreadAddressLable(); // ??ui if (currentTabIndex == INDEX_FRIENDS_MAIN) { friendsListFragment.refresh(); } } /** * ?msg * * @param msg */ private void saveInviteMsg(InviteMessage msg) { // ?msg inviteMessgeDao.saveMessage(msg); // 1 User user = MyApplication.getInstance().getContactList(false).get(Constant.NEW_FRIENDS_USERNAME); if (user != null && user.getUnreadMsgCount() == 0) { user.setUnreadMsgCount(user.getUnreadMsgCount() + 1); } } /** * ? */ 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 (((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList(false) .get(Constant.NEW_FRIENDS_USERNAME) != null) unreadAddressCountTotal = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList(false) .get(Constant.NEW_FRIENDS_USERNAME).getUnreadMsgCount(); return unreadAddressCountTotal; } /** * ? */ @Override public void onEvent(EMNotifierEvent event) { // switch (event.getEvent()) { case EventNewCMDMessage: break; case EventOfflineMessage: refreshUI(); break; case EventNewMessage: // ? { final EMMessage message = (EMMessage) event.getData(); // String type = message.getStringAttribute("vote", null); // if (type == null) { final String toChatUsername = message.getFrom(); // final UserDao userdao = new UserDao(MainActivity.this); User local_user = userDao.getUser(toChatUsername, false); if (message.getBooleanAttribute("pay", false)) { try { double money = Double.valueOf(message.getStringAttribute("money", "0.00")); PreferenceUtils.getInstance(MainActivity.this).setSettingUserMoney(String.valueOf((money))); } catch (Exception e) { // } } if (toChatUsername.equals("admin") || toChatUsername.equals("kefu")) { // User user = new User("admin"); // user.setNick(""); // userdao.saveContact(user); HXSDKHelper.getInstance().getNotifier().onNewMsg(message); refreshUI(); } else { if (local_user == null) { local_user = new User(); if (message.getBooleanAttribute("bool", false)) { local_user.setUsername(toChatUsername); local_user.setUser_id(message.getIntAttribute("uid", 0)); local_user.setNick(message.getStringAttribute("nick", "")); local_user.setLogo(message.getStringAttribute("logo", "")); local_user.setIs_friend(false); userDao.saveContact(local_user); } } else { HXSDKHelper.getInstance().getNotifier().onNewMsg(message); refreshUI(); } } // } else if (type.equals("vote")) { // String info = message.getStringAttribute("info", null); // if (info != null) { // userDao.addVoteMessage(info); // if (settingFragment != null) // settingFragment.refreshVoteMessage(); // } // } break; } case EventConversationListChanged: { refreshUI(); break; } default: break; } } private void refreshUI() { runOnUiThread(new Runnable() { public void run() { // bottom bar? updateUnreadLabel(); if (currentTabIndex == INDEX_MESSAGE_MAIN) { // ?????? if (chatMessageFragment != null) { chatMessageFragment.refresh(); } } } }); } /** * ? */ public void updateUnreadLabel() { int count = getUnreadMsgCountTotal(); if (count > 0) { unreadLabel.setText(String.valueOf(count)); unreadLabel.setVisibility(View.VISIBLE); } else { unreadLabel.setVisibility(View.INVISIBLE); } } /** * ?? * * @return */ public int getUnreadMsgCountTotal() { int unreadMsgCountTotal = 0; int chatroomUnreadMsgCount = 0; unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount(); for (EMConversation conversation : EMChatManager.getInstance().getAllConversations().values()) { if (conversation.getType() == EMConversationType.ChatRoom) chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount(); } return unreadMsgCountTotal - chatroomUnreadMsgCount; } /** * 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; } public void loadQuanInfo() {// 01-27 18:56:19.365: I/System.out(2626): uid=886&token=704afe073992cbe4813cae2f7715336f canGetQuan = false; long resumeTime = System.currentTimeMillis(); if (resumeTime - stopTime > 2000) { UserDao dao = new UserDao(this); List<User> users = dao.getUserList(); RequestParams params = new RequestParams(); if (users != null) { Set<String> set = new HashSet<String>(); for (int i = 0; i < users.size(); i++) { set.add(users.get(i).getUser_id() + ""); } params.put("users[]", set); } params.put("add_code", add_code); HttpRestClient.post(Constant.NEW_GET_NOW, params, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { // System.out.println("**** " + responseString); if (!CommonUtils.isNullOrEmpty(responseString)) { Map<String, Object> m = JsonToMapList.getMap(responseString); if (m != null && !CommonUtils.isNullOrEmpty(m.get("ok")) && m.get("ok").toString().equals("1")) { Map<String, Object> map = JsonToMapList.getMap(m.get("data").toString()); if (map != null) { if (!CommonUtils.isNullOrEmpty(map) && !CommonUtils.isNullOrEmpty(map.get("quan"))) { if (map.get("quan").toString().equals("1")) { runOnUiThread(new Runnable() { public void run() { hasNewQaun = true; unreadQuanLabel.setVisibility(View.VISIBLE); if (selectCityFrament != null) selectCityFrament.hasRead(); } }); } } if (!CommonUtils.isNullOrEmpty(map) && !CommonUtils.isNullOrEmpty(map.get("notice"))) { if (map.get("notice").toString().equals("1")) { runOnUiThread(new Runnable() { public void run() { hasNewNotice = true; unreadQuanLabel.setVisibility(View.VISIBLE); if (selectCityFrament != null) selectCityFrament.setNoticeShow(); } }); } } if (!CommonUtils.isNullOrEmpty(map) && !CommonUtils.isNullOrEmpty(map.get("notice2"))) { if (map.get("notice2").toString().equals("1")) { runOnUiThread(new Runnable() { public void run() { hasNewNotice2 = true; unreadQuanLabel.setVisibility(View.VISIBLE); if (selectCityFrament != null) selectCityFrament.setNotice2Show(); } }); } } } } } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { // System.out.println("rrrr" + responseString); } }); } } @Override protected void onResume() { super.onResume(); if (canGetQuan) loadQuanInfo(); if (!isConflict && !isCurrentAccountRemoved) { updateUnreadLabel(); updateUnreadAddressLable(); EMChatManager.getInstance().activityResumed(); } if (!hasNewQaun && !hasNewNotice && !hasNewNotice2) { unreadQuanLabel.setVisibility(View.INVISIBLE); } else { unreadQuanLabel.setVisibility(View.VISIBLE); } // unregister this event listener when this activity enters the background DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper.getInstance(); sdkHelper.pushActivity(this); // register the event listener when enter the foreground EMChatManager.getInstance().registerEventListener(this, new EMNotifierEvent.Event[] { EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventConversationListChanged }); } @Override protected void onStop() { System.out.println("*******************************************"); EMChatManager.getInstance().unregisterEventListener(this); DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper.getInstance(); sdkHelper.popActivity(this); canGetQuan = true; stopTime = System.currentTimeMillis(); super.onStop(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean("isConflict", isConflict); outState.putBoolean(Constant.ACCOUNT_REMOVED, isCurrentAccountRemoved); super.onSaveInstanceState(outState); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (isTaskRoot()) { moveTaskToBack(false); } else { moveTaskToBack(true); } return true; } return super.onKeyDown(keyCode, event); } public void sendMatch() { } void logout() { final ProgressDialog pd = new ProgressDialog(MainActivity.this); String st = "..."; pd.setMessage(st); pd.setCanceledOnTouchOutside(false); pd.show(); DemoHXSDKHelper.getInstance().logout(true, new EMCallBack() { @Override public void onSuccess() { MainActivity.this.runOnUiThread(new Runnable() { public void run() { pd.dismiss(); // ?? MainActivity.this.finish(); startActivity(new Intent(MainActivity.this, LoginActivity.class)); } }); } @Override public void onProgress(int progress, String status) { } @Override public void onError(int code, String message) { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { // pd.dismiss(); Toast.makeText(MainActivity.this, "unbind devicetokens failed", Toast.LENGTH_SHORT).show(); } }); } }); } /** * onActivityResult */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == MAIN_MESSAGE_LOGIN_OUT) { // ? logout(); } else if (resultCode == MAIN_MESSAGE_SYSTEM_OUT) { // ? MainActivity.this.finish(); android.os.Process.killProcess(android.os.Process.myPid()); // ?PID System.exit(0); // java?c#0 } else if (resultCode == 888) { settingFragment.InitData(true); } else if (resultCode == 369) { add_code = data.getIntExtra("id", 0); selectCityFrament.setAddress(add_code, data.getStringExtra("name")); } } /** * ??? */ public void hideNavigationBar() { int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar | View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar if (android.os.Build.VERSION.SDK_INT >= 19) { uiFlags |= 0x00001000; // SYSTEM_UI_FLAG_IMMERSIVE_STICKY: hide navigation bars - compatibility: building API level is lower thatn 19, use magic number directly for higher API target level } else { uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE; } getWindow().getDecorView().setSystemUiVisibility(uiFlags); } }