package com.fanxin.huangfangyi.main.fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.util.Log; import android.util.Pair; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.easemob.redpacketui.RedPacketConstant; import com.fanxin.huangfangyi.Constant; import com.fanxin.huangfangyi.DemoHelper; import com.fanxin.huangfangyi.R; import com.fanxin.huangfangyi.db.InviteMessgeDao; import com.fanxin.huangfangyi.main.activity.ChatActivity; import com.fanxin.huangfangyi.main.adapter.ConversationAdapter; import com.fanxin.easeui.EaseConstant; import com.fanxin.easeui.widget.EaseConversationList; import com.hyphenate.EMConnectionListener; import com.hyphenate.EMConversationListener; import com.hyphenate.EMError; import com.hyphenate.chat.EMClient; import com.hyphenate.chat.EMConversation; import com.hyphenate.chat.EMConversation.EMConversationType; import com.hyphenate.chat.EMMessage; import com.hyphenate.exceptions.HyphenateException; import com.hyphenate.util.NetUtils; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; public class ConversationListFragment extends Fragment { private TextView errorText; private final static int MSG_REFRESH = 2; protected EditText query; protected ImageButton clearSearch; protected boolean hidden; protected List<EMConversation> conversationList = new ArrayList<EMConversation>(); protected EaseConversationList conversationListView; protected FrameLayout errorItemContainer; protected boolean isConflict; protected EMConversationListener convListener = new EMConversationListener() { @Override public void onCoversationUpdate() { refresh(); } }; private MyBroadcastReceiver broadcastReceiver; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fx_fragment_conversation, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) return; super.onActivityCreated(savedInstanceState); initView(); setUpView(); broadcastReceiver=new MyBroadcastReceiver(); IntentFilter filter=new IntentFilter(); filter.addAction(EaseConstant.ACTION_DELETE_MSG); getActivity().registerReceiver(broadcastReceiver,filter); } protected void initView() { errorItemContainer = (FrameLayout) getView().findViewById(R.id.fl_error_item); View errorView = View.inflate(getActivity(), R.layout.em_chat_neterror_item, null); errorItemContainer.addView(errorView); errorText = (TextView) errorView.findViewById(R.id.tv_connect_errormsg); conversationListView = (EaseConversationList) getView().findViewById(R.id.list); } protected void setUpView() { conversationList.addAll(loadConversationList()); ConversationAdapter adapter = new ConversationAdapter(getContext(), 0, conversationList); conversationListView.init(conversationList, adapter); if (listItemClickListener != null) { conversationListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { EMConversation conversation = conversationListView.getItem(position); listItemClickListener.onListItemClicked(conversation); } }); } EMClient.getInstance().addConnectionListener(connectionListener); // register context menu registerForContextMenu(conversationListView); conversationListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { EMConversation conversation = conversationListView.getItem(position); String username = conversation.getUserName(); if (username.equals(EMClient.getInstance().getCurrentUser())) Toast.makeText(getActivity(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show(); else { // start chat acitivity Intent intent = new Intent(getActivity(), ChatActivity.class); if (conversation.isGroup()) { if (conversation.getType() == EMConversationType.ChatRoom) { // it's group chat intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_CHATROOM); } else { intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP); } } // it's single chat intent.putExtra(Constant.EXTRA_USER_ID, username); startActivity(intent); } } }); conversationListView.setConversationListHelper(new EaseConversationList.EaseConversationListHelper() { @Override public String onSetItemSecondaryText(EMMessage lastMessage) { if (lastMessage.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) { try { String sendNick = lastMessage.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_NAME); String receiveNick = lastMessage.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_NAME); String msg; if (lastMessage.direct() == EMMessage.Direct.RECEIVE) { msg = String.format(getResources().getString(R.string.msg_someone_take_red_packet), receiveNick); } else { if (sendNick.equals(receiveNick)) { msg = getResources().getString(R.string.msg_take_red_packet); } else { msg = String.format(getResources().getString(R.string.msg_take_someone_red_packet), sendNick); } } return msg; } catch (HyphenateException e) { e.printStackTrace(); } } return null; } }); } protected void onConnectionDisconnected() { errorItemContainer.setVisibility(View.VISIBLE); if (NetUtils.hasNetwork(getActivity())) { errorText.setText(R.string.can_not_connect_chat_server_connection); } else { errorText.setText(R.string.the_current_network); } } public List<EMConversation> loadConversationList() { // get all conversations Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations(); List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>(); /** * lastMsgTime will change if there is new message during sorting * so use synchronized to make sure timestamp of last message won't change. */ synchronized (conversations) { for (EMConversation conversation : conversations.values()) { if (conversation.getAllMessages().size() != 0 && conversation.getType() != EMConversation.EMConversationType.ChatRoom ) { if((conversation.getType() == EMConversation.EMConversationType.Chat && !DemoHelper.getInstance().getContactList().containsKey(conversation.getUserName()))){ }else{ try { sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation)); } catch (NullPointerException e) { } } } } } try { // Internal is TimSort algorithm, has bug sortConversationByLastChatTime(sortList); } catch (Exception e) { e.printStackTrace(); } List<EMConversation> list = new ArrayList<EMConversation>(); for (Pair<Long, EMConversation> sortItem : sortList) { list.add(sortItem.second); } return list; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { getActivity().getMenuInflater().inflate(R.menu.em_delete_message, menu); } @Override public boolean onContextItemSelected(MenuItem item) { boolean deleteMessage = false; if (item.getItemId() == R.id.delete_message) { deleteMessage = true; } else if (item.getItemId() == R.id.delete_conversation) { deleteMessage = false; } EMConversation tobeDeleteCons = conversationListView.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position); if (tobeDeleteCons == null) { return true; } try { // delete conversation EMClient.getInstance().chatManager().deleteConversation(tobeDeleteCons.getUserName(), deleteMessage); InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity()); inviteMessgeDao.deleteMessage(tobeDeleteCons.getUserName()); } catch (Exception e) { e.printStackTrace(); } refresh(); // update unread count ((MainActivity) getActivity()).updateUnreadLabel(); return true; } protected EMConnectionListener connectionListener = new EMConnectionListener() { @Override public void onDisconnected(int error) { if (error == EMError.USER_REMOVED || error == EMError.USER_LOGIN_ANOTHER_DEVICE) { isConflict = true; } else { handler.sendEmptyMessage(0); } } @Override public void onConnected() { handler.sendEmptyMessage(1); } }; private EaseConversationListItemClickListener listItemClickListener; protected Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 0: onConnectionDisconnected(); break; case 1: onConnectionConnected(); break; case MSG_REFRESH: { conversationList.clear(); conversationList.addAll(loadConversationList()); conversationListView.refresh(); Log.d("coversation--->", "refresh"); break; } default: break; } } }; /** * connected to server */ protected void onConnectionConnected() { errorItemContainer.setVisibility(View.GONE); } /** * refresh ui */ public void refresh() { if (!handler.hasMessages(MSG_REFRESH)) { handler.sendEmptyMessage(MSG_REFRESH); } } /** * sort conversations according time stamp of last message * * @param conversationList */ public void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) { Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() { @Override public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) { if (con1.first == con2.first) { return 0; } else if (con2.first > con1.first) { return 1; } else { return -1; } } }); } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); this.hidden = hidden; if (!hidden && !isConflict) { refresh(); } } @Override public void onResume() { super.onResume(); if (!hidden) { refresh(); } } @Override public void onDestroy() { super.onDestroy(); EMClient.getInstance().removeConnectionListener(connectionListener); getActivity().unregisterReceiver(broadcastReceiver); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (isConflict) { outState.putBoolean("isConflict", true); } } public interface EaseConversationListItemClickListener { /** * click event for conversation list * * @param conversation -- clicked item */ void onListItemClicked(EMConversation conversation); } /** * set conversation list item click listener * * @param listItemClickListener */ public void setConversationListItemClickListener(EaseConversationListItemClickListener listItemClickListener) { this.listItemClickListener = listItemClickListener; } class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("receive-->","broadcast"); refresh(); } } }