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.indoorsy.frash.easemob.activity; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Locale; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.media.ThumbnailUtils; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.support.v4.view.ViewPager; import android.text.ClipboardManager; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.Gravity; 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.Button; 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.EMCallBack; import com.easemob.chat.CmdMessageBody; import com.easemob.chat.EMChatManager; import com.easemob.chat.EMConversation; import com.easemob.chat.EMGroup; import com.easemob.chat.EMMessage; import com.easemob.chat.EMMessage.ChatType; import com.easemob.chat.ImageMessageBody; import com.easemob.chat.TextMessageBody; import com.easemob.util.EMLog; import com.easemob.util.PathUtil; import com.indoorsy.frash.Constants; import com.indoorsy.frash.R; import com.indoorsy.frash.common.activity.BasicActivity; import com.indoorsy.frash.common.view.CustomTitleView; import com.indoorsy.frash.easemob.adapter.ExpressionAdapter; import com.indoorsy.frash.easemob.adapter.ExpressionPagerAdapter; import com.indoorsy.frash.easemob.adapter.MessageAdapter; import com.indoorsy.frash.easemob.util.CommonUtils; import com.indoorsy.frash.easemob.util.SmileUtils; import com.indoorsy.frash.easemob.widget.ExpandGridView; import com.indoorsy.frash.easemob.widget.PasteEditText; import com.indoorsy.frash.http.core.HttpResult; import com.indoorsy.frash.http.core.HttpTask; import com.indoorsy.frash.util.ImageUtil; import com.indoorsy.frash.util.ToastUtil; /** * ?? * */ @SuppressWarnings("deprecation") @SuppressLint("SdCardPath") public class ChatActivity extends BasicActivity { public static final int REQUEST_CODE_CONTEXT_MENU = 3; public static final int REQUEST_CODE_TEXT = 5; public static final int REQUEST_CODE_VOICE = 6; public static final int REQUEST_CODE_PICTURE = 7; public static final int REQUEST_CODE_LOCATION = 8; public static final int REQUEST_CODE_NET_DISK = 9; public static final int REQUEST_CODE_FILE = 10; public static final int REQUEST_CODE_COPY_AND_PASTE = 11; public static final int REQUEST_CODE_PICK_VIDEO = 12; public static final int REQUEST_CODE_DOWNLOAD_VIDEO = 13; public static final int REQUEST_CODE_VIDEO = 14; public static final int REQUEST_CODE_DOWNLOAD_VOICE = 15; public static final int REQUEST_CODE_SELECT_USER_CARD = 16; public static final int REQUEST_CODE_SEND_USER_CARD = 17; public static final int REQUEST_CODE_CAMERA = 18; public static final int REQUEST_CODE_LOCAL = 19; public static final int REQUEST_CODE_CLICK_DESTORY_IMG = 20; public static final int REQUEST_CODE_GROUP_DETAIL = 21; public static final int REQUEST_CODE_SELECT_VIDEO = 23; public static final int REQUEST_CODE_SELECT_FILE = 24; public static final int REQUEST_CODE_ADD_TO_BLACKLIST = 25; 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 int CHATTYPE_GROUP = 2; public static final String COPY_IMAGE = "EASEMOBIMG"; private ListView listView; private PasteEditText mEditTextContent; private View buttonSetModeKeyboard; private View buttonSend; private LinearLayout emojiIconContainer; private LinearLayout btnContainer; private View more; private View more_new; private ClipboardManager clipboard; private ViewPager expressionViewpager; private InputMethodManager manager; private List<String> reslist; private int chatType; private EMConversation conversation; private NewMessageBroadcastReceiver receiver; public static ChatActivity activityInstance = null; // ???? private String toChatUsername; private MessageAdapter adapter; private File cameraFile; static int resendPos; private TextView mTextView1, mTextView2, mTextView3, mTextView4; private ImageView iv_emoticons_normal; private ImageView iv_emoticons_checked; private RelativeLayout edittext_layout; private ProgressBar loadmorePB; private boolean isloading; private final int pagesize = 20; private boolean haveMoreData = true; private Button btnMore; public String playMsgId, stImage, stPrice; private EMGroup group; private static boolean tag = true; private CustomTitleView customTitleView; @Override public void onClick(View v) { if (tag == true) { tag = false; sendCmdText(); } switch (v.getId()) { case R.id.leftImageView: this.finish(); break; case R.id.rightImageView: emptyHistory(); break; case R.id.btn_send:// ??(?) String s = mEditTextContent.getText().toString(); sendText(s); break; case R.id.btn_take_picture: selectPicFromCamera();// break; case R.id.btn_picture: selectPicFromLocal(); // break; case R.id.iv_emoticons_normal:// more.setVisibility(View.VISIBLE); more_new.setVisibility(View.GONE); iv_emoticons_normal.setVisibility(View.INVISIBLE); iv_emoticons_checked.setVisibility(View.VISIBLE); btnContainer.setVisibility(View.GONE); emojiIconContainer.setVisibility(View.VISIBLE); hideKeyboard(); break; case R.id.iv_emoticons_checked:// ?? iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); btnContainer.setVisibility(View.VISIBLE); emojiIconContainer.setVisibility(View.GONE); more.setVisibility(View.GONE); more_new.setVisibility(View.GONE); break; } } @Override public int initLayout() { return R.layout.indoorsy_chat; } @Override public void initUI() { customTitleView = (CustomTitleView) findViewById(R.id.customTitleView); customTitleView.setLeftImageBg(R.drawable.comm_back); customTitleView.setRightImageVisibility(View.VISIBLE); customTitleView.setRightImageBg(R.drawable.personal_manage_editor2); customTitleView.setVisibility(View.VISIBLE); customTitleView.setOnClickListener(this); stImage = getIntent().getStringExtra("image"); stPrice = getIntent().getStringExtra("price"); mTextView1 = (TextView) findViewById(R.id.textview_question1); mTextView2 = (TextView) findViewById(R.id.textview_question2); mTextView3 = (TextView) findViewById(R.id.textview_question3); mTextView4 = (TextView) findViewById(R.id.textview_question4); mTextView1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mEditTextContent.setText(getResources().getString(R.string.text_fahuo)); } }); mTextView2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mEditTextContent.setText(R.string.text_weight); } }); mTextView3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mEditTextContent.setText(R.string.text_color); } }); mTextView4.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mEditTextContent.setText(R.string.text_kuaidi); } }); listView = (ListView) findViewById(R.id.list); mEditTextContent = (PasteEditText) findViewById(R.id.et_sendmessage); buttonSetModeKeyboard = findViewById(R.id.btn_set_mode_keyboard); 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); btnContainer = (LinearLayout) findViewById(R.id.ll_btn_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); btnMore = (Button) findViewById(R.id.btn_more); iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); more = findViewById(R.id.more); more_new = findViewById(R.id.more_new); 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); more_new.setVisibility(View.GONE); iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); emojiIconContainer.setVisibility(View.GONE); btnContainer.setVisibility(View.GONE); } }); // ? mEditTextContent.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!TextUtils.isEmpty(s)) { btnMore.setVisibility(View.GONE); buttonSend.setVisibility(View.VISIBLE); } else { btnMore.setVisibility(View.VISIBLE); buttonSend.setVisibility(View.GONE); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); } @SuppressLint("ClickableViewAccessibility") @Override public void initData() { activityInstance = this; 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); SharedPreferences sharedPreFerences = getSharedPreferences("customernumber", Context.MODE_PRIVATE); toChatUsername = sharedPreFerences.getString("customerkey", Constants.CUSTOMERKEY); customTitleView.setTitle(toChatUsername); conversation = EMChatManager.getInstance().getConversation(toChatUsername); // ?0 conversation.resetUnreadMsgCount(); adapter = new MessageAdapter(this, toChatUsername, chatType); // ? listView.setAdapter(adapter); adapter.refresh(); listView.setOnScrollListener(new ListScrollListener()); int count = listView.getCount(); if (count > 0) { listView.setSelection(count - 1); } 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); btnContainer.setVisibility(View.GONE); return false; } }); // ? receiver = new NewMessageBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction()); // Mainacitivity,??chat?????? intentFilter.setPriority(5); registerReceiver(receiver, intentFilter); // ack?BroadcastReceiver IntentFilter ackMessageIntentFilter = new IntentFilter( EMChatManager.getInstance().getAckMessageBroadcastAction()); ackMessageIntentFilter.setPriority(5); registerReceiver(ackMessageReceiver, ackMessageIntentFilter); // ??BroadcastReceiver IntentFilter deliveryAckMessageIntentFilter = new IntentFilter( EMChatManager.getInstance().getDeliveryAckMessageBroadcastAction()); deliveryAckMessageIntentFilter.setPriority(5); registerReceiver(deliveryAckMessageReceiver, deliveryAckMessageIntentFilter); if (stImage == null) { } else { String stfirst = stImage.substring(0, 1); if (stfirst.equals("2")) { //? String pathOne = "/sdcard/appname/" + "one" + ".png"; saveImage(R.drawable.one, pathOne); //??image+ sendPicture(pathOne); } else if (stfirst.equals("")) { String pathTwo = "/sdcard/appname/" + "two" + ".png"; saveImage(R.drawable.two, pathTwo); sendPicture(pathTwo); } else if (stfirst.equals("?")) { String pathThree = "/sdcard/appname/" + "three" + ".png"; saveImage(R.drawable.three, pathThree); sendPicture(pathThree); } else if (stfirst.equals("?")) { String pathFour = "/sdcard/appname/" + "four" + ".png"; saveImage(R.drawable.four, pathFour); sendPicture(pathFour); } } } @Override public void onLoadFinish(HttpTask task, HttpResult result) { } /** * ? * */ private class NewMessageBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // abortBroadcast(); String username = intent.getStringExtra("from"); String msgid = intent.getStringExtra("msgid"); // message?db?id?mesage EMMessage message = EMChatManager.getInstance().getMessage(msgid); // ???group id if (message.getChatType() == ChatType.GroupChat) { username = message.getTo(); } if (!username.equals(toChatUsername)) { // ?????return notifyNewMessage(message); return; } // conversation = // EMChatManager.getInstance().getConversation(toChatUsername); // adapter?ui adapter.refresh(); listView.setSelection(listView.getCount() - 1); } } /** * 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.refresh(); listView.setSelection(data.getIntExtra("position", adapter.getCount()) - 1); break; default: break; } } if (resultCode == RESULT_OK) { // ? if (requestCode == REQUEST_CODE_CAMERA) { // ?? if (cameraFile != null && cameraFile.exists()) sendPicture(cameraFile.getAbsolutePath()); } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // ?? String videoPath = data.getStringExtra("path"); File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis()); Bitmap bitmap = null; FileOutputStream fos = null; try { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3); if (bitmap == null) { EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon"); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_panel_video_icon); } fos = new FileOutputStream(file); bitmap.compress(CompressFormat.JPEG, 100, fos); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } fos = null; } if (bitmap != null) { bitmap.recycle(); bitmap = null; } } } else if (requestCode == REQUEST_CODE_LOCAL) { // ?? if (data != null) { Uri selectedImage = data.getData(); if (selectedImage != null) { sendPicByUri(selectedImage); } } } else if (requestCode == REQUEST_CODE_TEXT || requestCode == REQUEST_CODE_VOICE || requestCode == REQUEST_CODE_PICTURE || requestCode == REQUEST_CODE_LOCATION || requestCode == REQUEST_CODE_VIDEO || requestCode == REQUEST_CODE_FILE) { resendMessage(); } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) { // if (!TextUtils.isEmpty(clipboard.getText())) { String pasteText = clipboard.getText().toString(); if (pasteText.startsWith(COPY_IMAGE)) { // ??path sendPicture(pasteText.replace(COPY_IMAGE, "")); } } } else if (conversation.getMsgCount() > 0) { adapter.refresh(); setResult(RESULT_OK); } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) { adapter.refresh(); } } } /** * ? */ public void selectPicFromCamera() { if (!CommonUtils.isExitsSdcard()) { ToastUtil.toast(getApplicationContext(), R.string.sd_not_find); return; } cameraFile = new File(PathUtil.getInstance().getImagePath(), System.currentTimeMillis() + ".jpg"); cameraFile.getParentFile().mkdirs(); startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)), REQUEST_CODE_CAMERA); } /** * ? */ public void selectPicFromLocal() { Intent intent; if (Build.VERSION.SDK_INT < 19) { intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); } else { intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); } startActivityForResult(intent, REQUEST_CODE_LOCAL); } /** * ??? * * @param content * message content * @param isResend * boolean resend */ private void sendText(String content) { if (content.length() > 0) { EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT); // ?chattype,?? if (chatType == CHATTYPE_GROUP) message.setChatType(ChatType.GroupChat); TextMessageBody txtBody = new TextMessageBody(content); // ?body message.addBody(txtBody); // ???,username?groupid message.setReceipt(toChatUsername); // messgageconversation conversation.addMessage(message); // adapter??adapter??message?sdk?? adapter.refresh(); listView.setSelection(listView.getCount() - 1); mEditTextContent.setText(""); setResult(RESULT_OK); } } /** * ??cmd? * * @param content * message content * @param isResend * boolean resend */ private void sendCmdText() { EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD); String action = "action1";//action?? // String action=getPhoneInfo(); CmdMessageBody cmdBody = new CmdMessageBody(action); String toUsername = "customers";//??? cmdMsg.setReceipt(toUsername); cmdMsg.setAttribute("deviceDetails", getPhoneInfo());//? cmdMsg.addBody(cmdBody); Log.i("log", "??"); EMChatManager.getInstance().sendMessage(cmdMsg, new EMCallBack() { @Override public void onSuccess() { Log.i("log", "???"); } @Override public void onProgress(int arg0, String arg1) { } @Override public void onError(int arg0, String arg1) { Log.i("log", "??"); } }); } private String getPhoneInfo() { String language = Locale.getDefault().getLanguage(); String phoneVersion = android.os.Build.VERSION.RELEASE; String xinghao = android.os.Build.MODEL; String firm = android.os.Build.MANUFACTURER; String versionName = null; try { versionName = getVersionName(); } catch (Exception e) { e.printStackTrace(); } String st = "{'clientLanguage':'" + language + "','clientVersion':'" + versionName + "','manufacturer':'" + firm + "','model':'" + xinghao + "','systemVersion':'" + phoneVersion + "'}"; return st; } private String getVersionName() throws Exception { // ?packagemanager PackageManager packageManager = getPackageManager(); // getPackageName()???0?? PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0); String version = packInfo.versionName; return version; } /** * ?? * * @param filePath */ private void sendPicture(final String filePath) { String to = toChatUsername; // create and add image message in view final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.IMAGE); // ?chattype,?? if (chatType == CHATTYPE_GROUP) message.setChatType(ChatType.GroupChat); message.setReceipt(to); ImageMessageBody body = new ImageMessageBody(new File(filePath)); // 100k?????? // body.setSendOriginalImage(true); message.addBody(body); conversation.addMessage(message); if (stImage != null) { message.setAttribute("name", stImage); message.setAttribute("price", stPrice); } listView.setAdapter(adapter); stImage = null; stPrice = null; adapter.refresh(); listView.setSelection(listView.getCount() - 1); setResult(RESULT_OK); // more(more); } /** * ?uri?? * * @param selectedImage */ private void sendPicByUri(Uri selectedImage) { // String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex("_data"); String picturePath = cursor.getString(columnIndex); cursor.close(); cursor = null; if (picturePath == null || picturePath.equals("null")) { Toast toast = Toast.makeText(this, R.string.not_find_image, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); return; } sendPicture(picturePath); } else { File file = new File(selectedImage.getPath()); if (!file.exists()) { Toast toast = Toast.makeText(this, R.string.not_find_image, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); return; } sendPicture(file.getAbsolutePath()); } } /** * ??? */ private void resendMessage() { EMMessage msg = null; msg = conversation.getMessage(resendPos); // msg.setBackSend(true); msg.status = EMMessage.Status.CREATE; adapter.refresh(); listView.setSelection(resendPos); } /** * ? * * @param view */ public void emptyHistory() { // ? EMChatManager.getInstance().clearConversation(toChatUsername); adapter.refresh(); } /** * ?? * * @param view */ public void more(View view) { if (more.getVisibility() == View.GONE) { System.out.println("more gone"); hideKeyboard(); more.setVisibility(View.VISIBLE); btnContainer.setVisibility(View.VISIBLE); emojiIconContainer.setVisibility(View.GONE); more_new.setVisibility(View.GONE); } else { if (emojiIconContainer.getVisibility() == View.VISIBLE) { emojiIconContainer.setVisibility(View.GONE); btnContainer.setVisibility(View.VISIBLE); iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); more_new.setVisibility(View.GONE); } else { more.setVisibility(View.GONE); more_new.setVisibility(View.GONE); } } } /** * ?? * * @param view */ public void more_new(View view) { if (more_new.getVisibility() == View.GONE) { System.out.println("more gone"); hideKeyboard(); more.setVisibility(View.GONE); more_new.setVisibility(View.VISIBLE); btnContainer.setVisibility(View.VISIBLE); emojiIconContainer.setVisibility(View.GONE); } else { iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); more.setVisibility(View.GONE); if (emojiIconContainer.getVisibility() == View.VISIBLE) { emojiIconContainer.setVisibility(View.GONE); btnContainer.setVisibility(View.VISIBLE); iv_emoticons_normal.setVisibility(View.VISIBLE); iv_emoticons_checked.setVisibility(View.INVISIBLE); } else { more_new.setVisibility(View.GONE); } } } /** * * * @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); } } /** * ?BroadcastReceiver */ private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { abortBroadcast(); String msgid = intent.getStringExtra("msgid"); String from = intent.getStringExtra("from"); EMConversation conversation = EMChatManager.getInstance().getConversation(from); if (conversation != null) { // message EMMessage msg = conversation.getMessage(msgid); if (msg != null) { msg.isAcked = true; } } adapter.notifyDataSetChanged(); } }; /** * ??BroadcastReceiver */ private BroadcastReceiver deliveryAckMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { abortBroadcast(); String msgid = intent.getStringExtra("msgid"); String from = intent.getStringExtra("from"); EMConversation conversation = EMChatManager.getInstance().getConversation(from); if (conversation != null) { // message EMMessage msg = conversation.getMessage(msgid); if (msg != null) { msg.isDelivered = true; } } adapter.notifyDataSetChanged(); } }; /** * ?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() { @SuppressWarnings("rawtypes") @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.indoorsy.frash.easemob.util.SmileUtils"); Field field = clz.getField(filename); mEditTextContent .append(SmileUtils.getSmiledText(ChatActivity.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; // try { unregisterReceiver(receiver); receiver = null; } catch (Exception e) { } try { unregisterReceiver(ackMessageReceiver); ackMessageReceiver = null; unregisterReceiver(deliveryAckMessageReceiver); deliveryAckMessageReceiver = null; } catch (Exception e) { } } @Override protected void onResume() { super.onResume(); if (group != null) customTitleView.setTitle(group.getGroupName()); adapter.refresh(); } /** * ?? */ private void hideKeyboard() { if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) { if (getCurrentFocus() != null) manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } /** * * * @param view */ public void back(View view) { hideKeyboard(); this.finish(); } /** * 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) { loadmorePB.setVisibility(View.VISIBLE); // sdk??20?db? List<EMMessage> messages; try { // ?messgesdb?messages // sdkconversation if (chatType == CHATTYPE_SINGLE) messages = conversation.loadMoreMsgFromDB(adapter.getItem(0).getMsgId(), pagesize); else messages = conversation.loadMoreGroupMsgFromDB(adapter.getItem(0).getMsgId(), pagesize); } catch (Exception e1) { loadmorePB.setVisibility(View.GONE); return; } try { Thread.sleep(300); } catch (InterruptedException e) { } if (messages.size() != 0) { // ui adapter.notifyDataSetChanged(); listView.setSelection(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) { SharedPreferences sharedPreFerences = getSharedPreferences("customernumber", Context.MODE_PRIVATE); String username = sharedPreFerences.getString("customerkey", Constants.CUSTOMERKEY); if (toChatUsername.equals(username)) super.onNewIntent(intent); else { finish(); startActivity(intent); } } /** * ?? * * @param forward_msg_id */ protected void forwardMessage(String forward_msg_id) { 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; case IMAGE: // ?? String filePath = ((ImageMessageBody) forward_msg.getBody()).getLocalUrl(); if (filePath != null) { File file = new File(filePath); if (!file.exists()) { // ??? filePath = ImageUtil.getThumbnailImagePath(filePath); } sendPicture(filePath); } break; default: break; } } public String getToChatUsername() { return toChatUsername; } /** * */ @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(); } } public void saveImage(int id, String path) { File f = new File(path); String dir = "/sdcard/appname/"; File createDir = new File(dir); if (!createDir.exists()) { createDir.mkdir(); } try { f.createNewFile(); } catch (IOException e) { } FileOutputStream fOut = null; try { fOut = new FileOutputStream(f); } catch (FileNotFoundException e) { e.printStackTrace(); } try { fOut.flush(); } catch (IOException e) { e.printStackTrace(); } try { fOut.close(); } catch (IOException e) { e.printStackTrace(); } } }