Java tutorial
/** * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved. * <p/> * 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.easemob.chatuidemo.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.text.ClipboardManager; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.easemob.EMEventListener; import com.easemob.EMNotifierEvent; import com.easemob.applib.controller.HXSDKHelper; import com.easemob.chat.EMChatManager; import com.easemob.chat.EMConversation; import com.easemob.chat.EMConversation.EMConversationType; import com.easemob.chat.EMGroup; import com.easemob.chat.EMMessage; import com.easemob.chat.EMMessage.ChatType; import com.easemob.chat.TextMessageBody; import com.easemob.chatuidemo.DemoHXSDKHelper; import com.easemob.chatuidemo.R; import com.easemob.chatuidemo.adapter.ExpressionAdapter; import com.easemob.chatuidemo.adapter.ExpressionPagerAdapter; import com.easemob.chatuidemo.adapter.MessageAdapter; import com.easemob.chatuidemo.domain.RobotUser; import com.easemob.chatuidemo.utils.SmileUtils; import com.easemob.chatuidemo.widget.ExpandGridView; import com.easemob.chatuidemo.widget.PasteEditText; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * ?? */ public abstract class BaseChatActivity extends FragmentActivity implements OnClickListener, EMEventListener { private static final String TAG = "ChatActivity"; private static final int REQUEST_CODE_EMPTY_HISTORY = 2; public static final int REQUEST_CODE_CONTEXT_MENU = 3; public static final int REQUEST_CODE_TEXT = 5; public static final int REQUEST_CODE_COPY_AND_PASTE = 11; public static final int RESULT_CODE_COPY = 1; public static final int RESULT_CODE_DELETE = 2; public static final int RESULT_CODE_FORWARD = 3; public static final int RESULT_CODE_OPEN = 4; public static final int RESULT_CODE_DWONLOAD = 5; public static final int RESULT_CODE_TO_CLOUD = 6; public static final int RESULT_CODE_EXIT_GROUP = 7; public static final int CHATTYPE_SINGLE = 1; public static final String COPY_IMAGE = "EASEMOBIMG"; private ListView listView; private PasteEditText mEditTextContent; private View buttonSend; // private ViewPager expressionViewpager; private LinearLayout emojiIconContainer; private View more; private int position; private ClipboardManager clipboard; private ViewPager expressionViewpager; private InputMethodManager manager; private List<String> reslist; private int chatType; private EMConversation conversation; public static BaseChatActivity activityInstance = null; // ???? private String toChatUsername; private MessageAdapter adapter; static int resendPos; private ImageView iv_emoticons_normal; private ImageView iv_emoticons_checked; private ProgressBar loadmorePB; private boolean isloading; private final int pagesize = 20; private boolean haveMoreData = true; private SwipeRefreshLayout swipeRefreshLayout; public boolean isRobot; public abstract int getContentViewId(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getContentViewId()); activityInstance = this; initView(); setUpView(); } View edittext_layout; /** * initView */ protected void initView() { listView = (ListView) findViewById(R.id.list); mEditTextContent = (PasteEditText) findViewById(R.id.et_sendmessage); edittext_layout = (RelativeLayout) findViewById(R.id.edittext_layout); buttonSend = findViewById(R.id.btn_send); expressionViewpager = (ViewPager) findViewById(R.id.vPager); emojiIconContainer = (LinearLayout) findViewById(R.id.ll_face_container); iv_emoticons_normal = (ImageView) findViewById(R.id.iv_emoticons_normal); iv_emoticons_checked = (ImageView) findViewById(R.id.iv_emoticons_checked); loadmorePB = (ProgressBar) findViewById(R.id.pb_load_more); iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); more = findViewById(R.id.more); edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_normal); // list reslist = getExpressionRes(35); // ?viewpager List<View> views = new ArrayList<View>(); View gv1 = getGridChildView(1); View gv2 = getGridChildView(2); views.add(gv1); views.add(gv2); expressionViewpager.setAdapter(new ExpressionPagerAdapter(views)); edittext_layout.requestFocus(); mEditTextContent.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_active); } else { edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_normal); } } }); mEditTextContent.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_active); more.setVisibility(View.GONE); iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); emojiIconContainer.setVisibility(View.GONE); } }); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.chat_swipe_layout); swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { if (listView.getFirstVisiblePosition() == 0 && !isloading && haveMoreData) { List<EMMessage> messages; try { if (chatType == CHATTYPE_SINGLE) { messages = conversation.loadMoreMsgFromDB(adapter.getItem(0).getMsgId(), pagesize); } else { messages = conversation.loadMoreGroupMsgFromDB(adapter.getItem(0).getMsgId(), pagesize); } } catch (Exception e1) { swipeRefreshLayout.setRefreshing(false); return; } if (messages.size() > 0) { adapter.notifyDataSetChanged(); adapter.refreshSeekTo(messages.size() - 1); if (messages.size() != pagesize) { haveMoreData = false; } } else { haveMoreData = false; } isloading = false; } else { Toast.makeText(BaseChatActivity.this, getResources().getString(R.string.no_more_messages), Toast.LENGTH_SHORT).show(); } swipeRefreshLayout.setRefreshing(false); } }, 1000); } }); } private void setUpView() { iv_emoticons_normal.setOnClickListener(this); iv_emoticons_checked.setOnClickListener(this); // position = getIntent().getIntExtra("position", -1); clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)) .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo"); // ??? chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE); if (chatType == CHATTYPE_SINGLE) { // ?? toChatUsername = getIntent().getStringExtra("userId"); Map<String, RobotUser> robotMap = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getRobotList(); if (robotMap != null && robotMap.containsKey(toChatUsername)) { isRobot = true; String nick = robotMap.get(toChatUsername).getNick(); if (!TextUtils.isEmpty(nick)) { setName(nick); } else { setName(toChatUsername); } } else { setName(toChatUsername); } } onConversationInit(); onListViewCreation(); } public abstract void setName(String name); protected void onConversationInit() { if (chatType == CHATTYPE_SINGLE) { conversation = EMChatManager.getInstance().getConversationByType(toChatUsername, EMConversationType.Chat); } // ?0 conversation.markAllMessagesAsRead(); // ?db?conversationgetChatOptions().getNumberOfMessagesLoaded // ??? final List<EMMessage> msgs = conversation.getAllMessages(); int msgCount = msgs != null ? msgs.size() : 0; if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) { String msgId = null; if (msgs != null && msgs.size() > 0) { msgId = msgs.get(0).getMsgId(); } if (chatType == CHATTYPE_SINGLE) { conversation.loadMoreMsgFromDB(msgId, pagesize); } else { conversation.loadMoreGroupMsgFromDB(msgId, pagesize); } } } protected void onListViewCreation() { adapter = new MessageAdapter(BaseChatActivity.this, toChatUsername, chatType); // ? listView.setAdapter(adapter); listView.setOnScrollListener(new ListScrollListener()); adapter.refreshSelectLast(); listView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { hideKeyboard(); more.setVisibility(View.GONE); iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); emojiIconContainer.setVisibility(View.GONE); return false; } }); } /** * onActivityResult */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_CODE_EXIT_GROUP) { setResult(RESULT_OK); finish(); return; } if (requestCode == REQUEST_CODE_CONTEXT_MENU) { switch (resultCode) { case RESULT_CODE_COPY: // ?? EMMessage copyMsg = ((EMMessage) adapter.getItem(data.getIntExtra("position", -1))); // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this, // ((TextMessageBody) copyMsg.getBody()).getMessage())); clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage()); break; case RESULT_CODE_DELETE: // ? EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1)); conversation.removeMessage(deleteMsg.getMsgId()); adapter.refreshSeekTo(data.getIntExtra("position", adapter.getCount()) - 1); break; case RESULT_CODE_FORWARD: // ?? break; default: break; } } if (resultCode == RESULT_OK) { // ? if (requestCode == REQUEST_CODE_EMPTY_HISTORY) { // ? EMChatManager.getInstance().clearConversation(toChatUsername); adapter.refresh(); // ??? } else if (requestCode == REQUEST_CODE_TEXT) { resendMessage(); } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) { // if (!TextUtils.isEmpty(clipboard.getText())) { String pasteText = clipboard.getText().toString(); } } } } /** * ? * * @param view */ @Override public void onClick(View view) { String st1 = getResources().getString(R.string.not_connect_to_server); int id = view.getId(); if (id == R.id.btn_send) {// ??(?) String s = mEditTextContent.getText().toString(); sendText(s); } else if (id == R.id.iv_emoticons_normal) { // more.setVisibility(View.VISIBLE); iv_emoticons_normal.setVisibility(View.INVISIBLE); iv_emoticons_checked.setVisibility(View.VISIBLE); emojiIconContainer.setVisibility(View.VISIBLE); hideKeyboard(); } else if (id == R.id.iv_emoticons_checked) { // ?? iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); emojiIconContainer.setVisibility(View.GONE); more.setVisibility(View.GONE); } } /** * ? * <p/> * see {@link EMNotifierEvent} */ @Override public void onEvent(EMNotifierEvent event) { switch (event.getEvent()) { case EventNewMessage: { //?message EMMessage message = (EMMessage) event.getData(); String username = null; //? if (message.getChatType() == ChatType.GroupChat || message.getChatType() == ChatType.ChatRoom) { username = message.getTo(); } else { //??? username = message.getFrom(); } //????? if (username.equals(getToChatUsername())) { refreshUIWithNewMessage(); //??? HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(message); } else { //????ID? HXSDKHelper.getInstance().getNotifier().onNewMsg(message); } break; } case EventDeliveryAck: { //?message refreshUI(); break; } case EventReadAck: { //?message refreshUI(); break; } case EventOfflineMessage: { refreshUI(); break; } default: break; } } private void refreshUIWithNewMessage() { if (adapter == null) { return; } runOnUiThread(new Runnable() { public void run() { adapter.refreshSelectLast(); } }); } private void refreshUI() { if (adapter == null) { return; } runOnUiThread(new Runnable() { public void run() { adapter.refresh(); } }); } /** * ??? */ public void sendText(String content) { if (content.length() > 0) { EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT); if (isRobot) { message.setAttribute("em_robot_message", true); } TextMessageBody txtBody = new TextMessageBody(content); // ?body message.addBody(txtBody); // ???,username?groupid message.setReceipt(toChatUsername); // messgageconversation conversation.addMessage(message); // adapter??adapter??message?sdk?? adapter.refreshSelectLast(); mEditTextContent.setText(""); setResult(RESULT_OK); } } /** * ??? */ private void resendMessage() { EMMessage msg = null; msg = conversation.getMessage(resendPos); // msg.setBackSend(true); msg.status = EMMessage.Status.CREATE; adapter.refreshSeekTo(resendPos); } /** * * * @param view */ public void setModeKeyboard(View view) { // mEditTextContent.setOnFocusChangeListener(new OnFocusChangeListener() // { // @Override // public void onFocusChange(View v, boolean hasFocus) { // if(hasFocus){ // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); // } // } // }); more.setVisibility(View.GONE); view.setVisibility(View.GONE); mEditTextContent.requestFocus(); } /** * ? */ public void emptyHistory() { String st5 = getResources().getString(R.string.Whether_to_empty_all_chats); startActivityForResult(new Intent(this, AlertDialog.class).putExtra("titleIsCancel", true) .putExtra("msg", st5).putExtra("cancel", true), REQUEST_CODE_EMPTY_HISTORY); } /** * * * @param v */ public void editClick(View v) { listView.setSelection(listView.getCount() - 1); if (more.getVisibility() == View.VISIBLE) { more.setVisibility(View.GONE); iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); } } private PowerManager.WakeLock wakeLock; /** * ?gridview?view * * @param i * @return */ private View getGridChildView(int i) { View view = View.inflate(this, R.layout.expression_gridview, null); ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview); List<String> list = new ArrayList<String>(); if (i == 1) { List<String> list1 = reslist.subList(0, 20); list.addAll(list1); } else if (i == 2) { list.addAll(reslist.subList(20, reslist.size())); } list.add("delete_expression"); final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, 1, list); gv.setAdapter(expressionAdapter); gv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String filename = expressionAdapter.getItem(position); try { // ???? // ????? // if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) { if (filename != "delete_expression") { // ? // ????SmileUtils Class clz = Class.forName("com.easemob.chatuidemo.utils.SmileUtils"); Field field = clz.getField(filename); mEditTextContent .append(SmileUtils.getSmiledText(BaseChatActivity.this, (String) field.get(null))); } else { // if (!TextUtils.isEmpty(mEditTextContent.getText())) { int selectionStart = mEditTextContent.getSelectionStart();// ?? if (selectionStart > 0) { String body = mEditTextContent.getText().toString(); String tempStr = body.substring(0, selectionStart); int i = tempStr.lastIndexOf("[");// ??? if (i != -1) { CharSequence cs = tempStr.substring(i, selectionStart); if (SmileUtils.containsKey(cs.toString())) mEditTextContent.getEditableText().delete(i, selectionStart); else mEditTextContent.getEditableText().delete(selectionStart - 1, selectionStart); } else { mEditTextContent.getEditableText().delete(selectionStart - 1, selectionStart); } } } // } } } catch (Exception e) { } } }); return view; } public List<String> getExpressionRes(int getSum) { List<String> reslist = new ArrayList<String>(); for (int x = 1; x <= getSum; x++) { String filename = "ee_" + x; reslist.add(filename); } return reslist; } @Override protected void onDestroy() { super.onDestroy(); activityInstance = null; } @Override protected void onResume() { super.onResume(); if (adapter != null) { adapter.refresh(); } 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.EventDeliveryAck, EMNotifierEvent.Event.EventReadAck }); } @Override protected void onStop() { // unregister this event listener when this activity enters the // background EMChatManager.getInstance().unregisterEventListener(this); DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper.getInstance(); // activity foreground activity sdkHelper.popActivity(this); super.onStop(); } @Override protected void onPause() { super.onPause(); if (wakeLock.isHeld()) wakeLock.release(); } /** * ?? */ private void hideKeyboard() { if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) { if (getCurrentFocus() != null) manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } /** * */ public void back() { EMChatManager.getInstance().unregisterEventListener(this); finish(); } /** * */ @Override public void onBackPressed() { if (more.getVisibility() == View.VISIBLE) { more.setVisibility(View.GONE); iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); } else { super.onBackPressed(); } } /** * listview?listener */ private class ListScrollListener implements OnScrollListener { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { switch (scrollState) { case OnScrollListener.SCROLL_STATE_IDLE: /*if (view.getFirstVisiblePosition() == 0 && !isloading && haveMoreData && conversation.getAllMessages().size() != 0) { isloading = true; loadmorePB.setVisibility(View.VISIBLE); // sdk??20?db? List<EMMessage> messages; EMMessage firstMsg = conversation.getAllMessages().get(0); try { // ?messgesdb?messages // sdkconversation if (chatType == CHATTYPE_SINGLE) messages = conversation.loadMoreMsgFromDB(firstMsg.getMsgId(), pagesize); else messages = conversation.loadMoreGroupMsgFromDB(firstMsg.getMsgId(), pagesize); } catch (Exception e1) { loadmorePB.setVisibility(View.GONE); return; } try { Thread.sleep(300); } catch (InterruptedException e) { } if (messages.size() != 0) { // ui if (messages.size() > 0) { adapter.refreshSeekTo(messages.size() - 1); } if (messages.size() != pagesize) haveMoreData = false; } else { haveMoreData = false; } loadmorePB.setVisibility(View.GONE); isloading = false; }*/ break; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } } @Override protected void onNewIntent(Intent intent) { // notification bar??????? String username = intent.getStringExtra("userId"); if (toChatUsername.equals(username)) super.onNewIntent(intent); else { finish(); startActivity(intent); } } /** * ?? * * @param forward_msg_id */ protected void forwardMessage(String forward_msg_id) { final EMMessage forward_msg = EMChatManager.getInstance().getMessage(forward_msg_id); EMMessage.Type type = forward_msg.getType(); switch (type) { case TXT: // ????? String content = ((TextMessageBody) forward_msg.getBody()).getMessage(); sendText(content); break; default: break; } } public String getToChatUsername() { return toChatUsername; } public ListView getListView() { return listView; } }