/yueai/src/main/java/com/yueai/activity/ChatActivity.java
Java | 1981 lines | 815 code | 105 blank | 1061 comment | 112 complexity | 1f9cd2475def9abff8c6790db19dedd0 MD5 | raw file
- package com.yueai.activity;
- import android.Manifest;
- import android.app.Activity;
- import android.app.Dialog;
- import android.content.Context;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.graphics.Color;
- import android.graphics.drawable.AnimationDrawable;
- import android.graphics.drawable.ColorDrawable;
- import android.graphics.drawable.Drawable;
- import android.net.Uri;
- import android.os.Handler;
- import android.os.Vibrator;
- import android.support.annotation.NonNull;
- import android.support.v4.app.ActivityCompat;
- import android.support.v4.content.ContextCompat;
- import android.support.v4.widget.SwipeRefreshLayout;
- import android.support.v7.widget.LinearLayoutManager;
- import android.support.v7.widget.RecyclerView;
- import android.text.TextUtils;
- import android.view.Display;
- import android.view.Gravity;
- import android.view.LayoutInflater;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.Window;
- import android.view.WindowManager;
- import android.widget.AdapterView;
- import android.widget.Button;
- import android.widget.ImageView;
- import android.widget.PopupWindow;
- import android.widget.RelativeLayout;
- import android.widget.TextView;
- import com.alibaba.fastjson.JSON;
- import com.library.dialog.OnDoubleDialogClickListener;
- import com.library.utils.DialogUtil;
- import com.library.utils.LogUtil;
- import com.library.utils.SharedPreferenceUtil;
- import com.library.utils.ToastUtil;
- import com.library.utils.Util;
- import com.library.utils.VersionInfoUtil;
- import com.library.widgets.AutoSwipeRefreshLayout;
- import com.library.widgets.ClearableEditText;
- import com.yueai.R;
- import com.yueai.adapter.ChatAdapter;
- import com.yueai.base.BaseTitleActivity;
- import com.yueai.bean.BaseModel;
- import com.yueai.bean.Image;
- import com.yueai.bean.Message;
- import com.yueai.bean.MessageList;
- import com.yueai.bean.WriteMsg;
- import com.yueai.constant.IConfigConstant;
- import com.yueai.constant.IUrlConstant;
- import com.yueai.event.MessageChangedEvent;
- import com.yueai.event.RefreshChatEvent;
- import com.yueai.fragment.MessageFragment;
- import com.yueai.haoping.ActionSheetDialog;
- import com.yueai.haoping.OnOperItemClickL;
- import com.yueai.online.MessageDao;
- import com.yueai.utils.FileUtil;
- import com.yueai.utils.GreenDaoUtil;
- import com.yueai.utils.RecordUtil;
- import com.yueai.utils.Utils;
- import com.yueai.xml.PlatformInfoXml;
- import com.yueai.xml.UserInfoXml;
- import com.zhy.http.okhttp.OkHttpUtils;
- import com.zhy.http.okhttp.callback.Callback;
- import org.greenrobot.eventbus.EventBus;
- import org.greenrobot.eventbus.Subscribe;
- import org.greenrobot.greendao.query.QueryBuilder;
- import java.io.File;
- import java.lang.ref.WeakReference;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import butterknife.BindView;
- import butterknife.OnClick;
- import okhttp3.Call;
- import okhttp3.Response;
- /**
- * 聊天页面
- * Created by zhangdroid on 2016/11/2.
- */
- public class ChatActivity extends BaseTitleActivity {
- @BindView(R.id.chat_swiperefresh)
- AutoSwipeRefreshLayout mAutoSwipeRefresh;
- @BindView(R.id.chat_RecyclerView)
- RecyclerView mRecyclerView;
- @BindView(R.id.chat_bottom_bar)
- RelativeLayout mRlChatBottom;
- @BindView(R.id.chat_operate_container)
- RelativeLayout mRlChatContainer;
- @BindView(R.id.chat_et_input)
- ClearableEditText mEtInput;
- @BindView(R.id.chat_send_msg)
- Button mBtnSend;// 发送文字消息
- @BindView(R.id.chat_send_photo)
- ImageView mIvSendPhoto;// 发送图片
- @BindView(R.id.chat_intercept)
- TextView mTvIntercept;
- // 语音
- @BindView(R.id.chat_msg_switch)
- ImageView mIvChatSwitch;
- @BindView(R.id.record)
- Button mBtnRecord;
- /**
- * 用户id
- */
- private String mUserId;
- /**
- * 用户昵称
- */
- private String mNickname;
- /**
- * 用户头像url
- */
- private String mAvatarUrl;
- private ChatAdapter mChatAdapter;
- private LinearLayoutManager mLinearLayoutManager;
- // 录音框
- private PopupWindow mRecordPopupWindow;
- private static final int PERMISSION_CODE_RECORD_AUDIO = 0;
- private static final int PERMISSION_CODE_WRITE_EXTERNAL_STORAGE = 1;
- private static final int MSG_TYPE_TIMER = 1;
- // 录音文件路径
- private String mOutputPath;
- // 录音文件名
- private String mRecordFileName;
- // 是否正在录音
- private boolean mIsRecording;
- // 录音是否被取消
- private boolean mIsRecordCanceled;
- // 录音时长(毫秒)
- private long mRecordDuration;
- // 录音计时刷新间隔(毫秒)
- private final long mRefreshInterval = 250;
- // 计算录音时长的Handler
- private Handler mTimerHandler = new Handler() {
- @Override
- public void handleMessage(android.os.Message msg) {
- super.handleMessage(msg);
- switch (msg.what) {
- case MSG_TYPE_TIMER:
- if (mIsRecording) {
- // 计时
- mRecordDuration += mRefreshInterval;
- // 录音超过1分钟自动发送
- if (mRecordDuration > 60 * 1000) {
- stopRecordAndSend();
- } else {
- mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_TIMER, mRefreshInterval);
- }
- }
- break;
- }
- }
- };
- private Message msg;
- // 录音状态常量
- private enum STATE {
- /**
- * 默认值
- */
- IDLE,
- /**
- * 录音中
- */
- RECORDING,
- /**
- * 取消
- */
- CANCELED,
- /**
- * 录音时间太短
- */
- TOO_SHORT
- }
- private boolean mIsShowSendVipByPraise = false;
- private boolean mIsShowWriteMsgIntercept = false;
- private static final String INTENT_KEY_UID = "key_userId";
- private static final String INTENT_KEY_NICKNAME = "key_nickname";
- private static final String INTENT_KEY_AVATAR_URL = "key_avatar_url";
- private Dialog dialog;
- /**
- * 跳转聊天页
- *
- * @param from
- * @param userId 用户id
- * @param nickname 用户昵称
- * @param avatarUrl 用户头像url
- */
- public static void toChatActivity(Activity from, String userId, String nickname, String avatarUrl) {
- Map<String, String> map = new HashMap<String, String>();
- map.put(INTENT_KEY_UID, userId);
- map.put(INTENT_KEY_NICKNAME, nickname);
- map.put(INTENT_KEY_AVATAR_URL, avatarUrl);
- Util.gotoActivity(from, ChatActivity.class, false, map);
- }
- /**
- * 跳转聊天页
- *
- * @param context
- * @param userId 用户id
- * @param nickname 用户昵称
- * @param avatarUrl 用户头像url
- */
- public static void toChatActivity(Context context, String userId, String nickname, String avatarUrl) {
- Intent intent = new Intent(context, ChatActivity.class);
- intent.putExtra(INTENT_KEY_UID, userId);
- intent.putExtra(INTENT_KEY_NICKNAME, nickname);
- intent.putExtra(INTENT_KEY_AVATAR_URL, avatarUrl);
- context.startActivity(intent);
- }
- @Override
- protected int getLayoutResId() {
- return R.layout.activity_chat;
- }
- @Override
- protected String getCenterTitle() {
- return null;
- }
- @Override
- protected void initViewsAndVariables() {
- //// /**加载读信拦截对话框**/
- // boolean showDalog = SharedPreferenceUtil.getBooleanValue(Utils.getContext(), "INTERCEPT_DIALOG", "DIALOG", true);
- // if(showDalog){
- // mTvIntercept.setVisibility(View.VISIBLE);
- // mRlChatContainer.setVisibility(View.GONE);
- // }
- Intent intent = getIntent();
- if (intent != null) {
- mUserId = intent.getStringExtra(INTENT_KEY_UID);
- mNickname = intent.getStringExtra(INTENT_KEY_NICKNAME);
- mAvatarUrl = intent.getStringExtra(INTENT_KEY_AVATAR_URL);
- }
- if (!TextUtils.isEmpty(mNickname)) {
- setTitle(mNickname);
- }
- // 设置下拉刷新动画样式
- mAutoSwipeRefresh.setColorSchemeResources(R.color.main_color);
- mAutoSwipeRefresh.setProgressBackgroundColorSchemeColor(Color.WHITE);
- mLinearLayoutManager = new LinearLayoutManager(this);
- mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
- mRecyclerView.setLayoutManager(mLinearLayoutManager);
- mChatAdapter = new ChatAdapter(this, -1);
- mRecyclerView.setAdapter(mChatAdapter);
- loadMsgList();
- }
- /**加载读信拦截的对话框**/
- private void showDialog() {
- dialog= new Dialog(this);
- LayoutInflater li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
- View v=li.inflate(R.layout.dialog_layout, null);
- dialog.setContentView(v);
- ImageView ivBack = (ImageView)v.findViewById(R.id.iv_back);
- Button btnUpgrade = (Button)v.findViewById(R.id.btn_upgrade);
- ivBack.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- finish();
- // dialog.dismiss();
- }
- });
- btnUpgrade.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- //添加好评送会员
- if (mIsShowSendVipByPraise) {
- ActionSheetDialogNoTitle();
- } else {
- BuyServiceActivity.toBuyServiceActivity(ChatActivity.this, BuyServiceActivity.INTENT_FROM_INTERCEPT,
- IConfigConstant.PAY_TAG_FROM_CHAT, IConfigConstant.PAY_WAY_ALL);
- }
- }
- });
- // dialog.setTitle("Custom Dialog");
- Window dialogWindow = dialog.getWindow();
- WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
- dialogWindow.setGravity(Gravity.LEFT | Gravity.BOTTOM);
- /*
- * 将对话框的大小按屏幕大小的百分比设置
- */
- WindowManager m = getWindowManager();
- Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
- p.height = (int) (d.getHeight() * 0.6); // 高度设置为屏幕的0.6
- p.width = (int) (d.getWidth() * 0.8); // 宽度设置为屏幕的0.65
- p.x = (int) (d.getWidth() * 0.135); // 新位置X坐标
- p.y = (int) (d.getHeight() * 0.24); // 新位置Y坐标
- // p.y = (int) (d.getHeight() * 0.1); // 新位置Y坐标
- // p.alpha = 1.0f; // 透明度
- // p.dimAmount = 0.7f;//黑暗度
- dialogWindow.setAttributes(p);
- // getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
- // WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
- // getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
- dialog.setCancelable(false);
- dialog.show();
- }
- /**根据是否是会员来判断拦截对话框的显示与否**/
- private void isShowDialog() {
- OkHttpUtils.post()
- .url(IUrlConstant.URL_GET_CHAT_MSG)
- .addHeader("token", PlatformInfoXml.getToken())
- .addParams("platformInfo", PlatformInfoXml.getPlatformJsonString())
- .addParams("uid", mUserId)
- .addParams("isUpdateUnPay", "0")
- .build()
- .execute(new Callback<MessageList>() {
- @Override
- public MessageList parseNetworkResponse(Response response, int id) throws Exception {
- String resultJson = response.body().string();
- if (!TextUtils.isEmpty(resultJson)) {
- return JSON.parseObject(resultJson, MessageList.class);
- }
- return null;
- }
- @Override
- public void onError(Call call, Exception e, int id) {
- stopRefresh(3);
- }
- @Override
- public void onResponse(MessageList response, int id) {
- if (response != null) {
- // 设置支付拦截
- String intercept = response.getShowWriteMsgIntercept();
- if (!TextUtils.isEmpty(intercept) && "1".equals(intercept)) {
- // dialog.show();
- // showDialog=true;
- showDialog();
- SharedPreferenceUtil.setBooleanValue(Utils.getContext(), "INTERCEPT_DIALOG", "DIALOG", true);
- } else {
- // 不展示拦截入口
- // dialog.dismiss();
- // showDialog=false;
- }
- }
- // stopRefresh(1);
- }
- });
- }
- @Override
- protected void addListeners() {
- // mIvLeft = (ImageView) findViewById(R.id.activity_base_iv_left);
- mIvLeft.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 刷新聊天列表
- EventBus.getDefault().post(new MessageChangedEvent());
- finish();
- }
- });
- mAutoSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
- @Override
- public void onRefresh() {
- loadMsgList();
- }
- });
- // 处理滑动冲突
- mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
- @Override
- public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
- super.onScrollStateChanged(recyclerView, newState);
- }
- @Override
- public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
- super.onScrolled(recyclerView, dx, dy);
- // 判断是否滑动到顶部
- int scrolledPosition = (mRecyclerView == null || mRecyclerView.getChildCount() == 0) ? 0 : mRecyclerView.getChildAt(0).getTop();
- mAutoSwipeRefresh.setEnabled(scrolledPosition >= 0);
- }
- });
- // 发送文字消息
- mEtInput.setTextWatcherCallback(new ClearableEditText.TextWatcherCallback() {
- @Override
- public void handleTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
- if (mEtInput.length() > 0) {
- mBtnSend.setVisibility(View.VISIBLE);
- mIvSendPhoto.setVisibility(View.GONE);
- } else {
- mBtnSend.setVisibility(View.GONE);
- mIvSendPhoto.setVisibility(View.VISIBLE);
- }
- }
- });
- // 切换文字/语音
- mIvChatSwitch.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- mIvChatSwitch.setSelected(!mIvChatSwitch.isSelected());
- if (mIvChatSwitch.isSelected()) { // 显示发送语音
- mBtnRecord.setText(getString(R.string.press_to_speak));
- mBtnRecord.setVisibility(View.VISIBLE);
- mEtInput.setVisibility(View.GONE);
- mBtnSend.setVisibility(View.GONE);
- mIvSendPhoto.setVisibility(View.GONE);
- if (mIsShowWriteMsgIntercept) {// 支付拦截时不可用
- mBtnRecord.setClickable(false);
- mBtnRecord.setEnabled(false);
- mBtnRecord.setTextColor(getResources().getColor(R.color.textcolor_light_gray));
- } else {
- mBtnRecord.setClickable(true);
- mBtnRecord.setEnabled(true);
- mBtnRecord.setTextColor(getResources().getColor(R.color.main_color));
- }
- } else { // 显示输入框
- mBtnRecord.setVisibility(View.GONE);
- mEtInput.setVisibility(View.VISIBLE);
- if (mEtInput.getText().length() > 0) {
- // 已经输入文字
- mBtnSend.setVisibility(View.VISIBLE);
- mIvSendPhoto.setVisibility(View.GONE);
- } else {
- mBtnSend.setVisibility(View.GONE);
- mIvSendPhoto.setVisibility(View.VISIBLE);
- }
- }
- }
- });
- // 发送语音消息
- mBtnRecord.setOnTouchListener(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- // 检查权限
- if (!checkPermissions()) {// 请求权限时不录音
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:// 按下时开始录音
- mBtnRecord.setText(getString(R.string.loose_to_end));
- showRecordPopupWindow(STATE.RECORDING);
- startRecord();
- mIsRecordCanceled = false;
- LogUtil.e(LogUtil.TAG_ZL, "ACTION_DOWN start()");
- break;
- case MotionEvent.ACTION_MOVE:
- if (event.getY() < -100) { // 上滑取消发送
- mIsRecordCanceled = true;
- showRecordPopupWindow(STATE.CANCELED);
- } else {
- mIsRecordCanceled = false;
- showRecordPopupWindow(STATE.RECORDING);
- }
- LogUtil.e(LogUtil.TAG_ZL, "ACTION_MOVE " + event.getY() + " mIsRecordCanceled = " + mIsRecordCanceled);
- break;
- case MotionEvent.ACTION_UP:// 松开时停止录音并发送
- mBtnRecord.setText(getString(R.string.press_to_speak));
- if (mIsRecordCanceled) {
- cancelRecord();
- LogUtil.e(LogUtil.TAG_ZL, "ACTION_UP canceld()");
- } else {
- stopRecordAndSend();
- LogUtil.e(LogUtil.TAG_ZL, "ACTION_UP stop()");
- }
- break;
- }
- }
- return true;
- }
- });
- // 发送图片
- mIvSendPhoto.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- GetPhotoActivity.toGetPhotoActivity(ChatActivity.this, IConfigConstant.LOCAL_PIC_PATH, new GetPhotoActivity.OnGetPhotoListener() {
- @Override
- public void getSelectedPhoto(File file) {
- if (file != null) {
- // 发送图片前显示要发送的图片进度
- Message message = new Message();
- if (mChatAdapter != null) {
- mChatAdapter.isShowImgLoading(true);
- mChatAdapter.isShowImgRetry(false);
- message.setUid(UserInfoXml.getUID());
- message.setMsgType("10");
- message.setCreateDateMills(System.currentTimeMillis());
- Image image = new Image();
- image.setIsMain(2);
- image.setThumbnailUrl(file.getAbsolutePath());
- image.setThumbnailUrlM(file.getAbsolutePath());
- image.setImageUrl(file.getAbsolutePath());
- message.setChatImage(image);
- mChatAdapter.insertItem(mChatAdapter.getItemCount(), message);
- // 滚动到底部
- mLinearLayoutManager.scrollToPosition(mChatAdapter.getItemCount() - 1);
- }
- sendPhotoMsg(file, message);
- }
- }
- });
- }
- });
- }
- private boolean checkPermissions() {
- boolean needRequestPermission = false;
- if (ContextCompat.checkSelfPermission(ChatActivity.this.getApplicationContext(),
- Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_DENIED) {
- needRequestPermission = true;
- // 请求android.permission.RECORD_AUDIO权限
- ActivityCompat.requestPermissions(ChatActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSION_CODE_RECORD_AUDIO);
- }
- if (ContextCompat.checkSelfPermission(ChatActivity.this.getApplicationContext(),
- Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
- needRequestPermission = true;
- // 请求android.permission.WRITE_EXTERNAL_STORAGE权限
- ActivityCompat.requestPermissions(ChatActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CODE_WRITE_EXTERNAL_STORAGE);
- }
- return needRequestPermission;
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults);
- }
- /**
- * 开始录音
- */
- private void startRecord() {
- // 录音开始前震动一下
- Vibrator vibrator = (Vibrator) ChatActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
- vibrator.vibrate(88);
- // 根据系统时间生成文件名
- mRecordFileName = FileUtil.createFileNameByTime() + ".mp3";
- // 录音文件保存路径: 根目录/DateLove/record/用户id/xxx.mp3
- mOutputPath = FileUtil.RECORD_DIRECTORY_PATH + File.separator + UserInfoXml.getUID() + File.separator + mRecordFileName;
- LogUtil.e(LogUtil.TAG_ZL, "录音存放路径:" + mOutputPath);
- // 开始录音
- RecordUtil.getInstance().startRecord(mOutputPath);
- mIsRecording = true;
- mRecordDuration = 0;
- // 计时,间隔250毫秒刷新
- mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_TIMER, mRefreshInterval);
- }
- /**
- * 停止录音并发送
- */
- private void stopRecordAndSend() {
- if (mIsRecording) {
- mIsRecording = false;
- LogUtil.e(LogUtil.TAG_ZL, "录音时长(毫秒):" + mRecordDuration);
- if (mRecordDuration < 1 * 1000) {// 录音时长小于1秒的不发送
- showRecordPopupWindow(STATE.TOO_SHORT);
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- // 延时500毫秒调用MediaRecorder#stop(),防止出现start()之后立马调用stop()的异常
- RecordUtil.getInstance().stopRecord();
- // 删除小于1秒的文件
- FileUtil.deleteFile(mOutputPath);
- }
- }, 500);
- } else {// 发送语音
- RecordUtil.getInstance().stopRecord();
- sendVoiceMsg();
- }
- // 隐藏录音框
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- if (mRecordPopupWindow != null && mRecordPopupWindow.isShowing()) {
- mRecordPopupWindow.dismiss();
- }
- }
- }, 500);
- }
- }
- /**
- * 录音取消,删除已经录制的文件
- */
- private void cancelRecord() {
- if (mIsRecordCanceled) {
- RecordUtil.getInstance().stopRecord();
- mIsRecordCanceled = false;
- FileUtil.deleteFile(mOutputPath);
- // 隐藏录音框
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- if (mRecordPopupWindow != null && mRecordPopupWindow.isShowing()) {
- mRecordPopupWindow.dismiss();
- }
- }
- }, 500);
- }
- }
- /**
- * 弹出录音框
- */
- private void showRecordPopupWindow(STATE state) {
- if (mRecordPopupWindow == null) {
- View contentView = LayoutInflater.from(ChatActivity.this).inflate(R.layout.popup_chat_record, null);
- mRecordPopupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.WRAP_CONTENT,
- WindowManager.LayoutParams.WRAP_CONTENT, true);
- mRecordPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
- }
- View view = mRecordPopupWindow.getContentView();
- if (view != null) {
- RelativeLayout rlRecording = (RelativeLayout) view.findViewById(R.id.popup_recording_container);
- ImageView ivRecording = (ImageView) view.findViewById(R.id.popup_record_anim);
- // 设置动画
- List<Drawable> drawableList = new ArrayList<Drawable>();
- drawableList.add(getResources().getDrawable(R.drawable.voice1));
- drawableList.add(getResources().getDrawable(R.drawable.voice2));
- drawableList.add(getResources().getDrawable(R.drawable.voice3));
- drawableList.add(getResources().getDrawable(R.drawable.voice4));
- drawableList.add(getResources().getDrawable(R.drawable.voice5));
- drawableList.add(getResources().getDrawable(R.drawable.voice6));
- AnimationDrawable animationDrawable = Utils.getFrameAnim(drawableList, true, 150);
- ivRecording.setImageDrawable(animationDrawable);
- ImageView ivCancel = (ImageView) view.findViewById(R.id.popup_cancel_record);
- ImageView ivTooShort = (ImageView) view.findViewById(R.id.popup_record_too_short);
- TextView tvState = (TextView) view.findViewById(R.id.popup_record_state);
- switch (state) {
- case RECORDING: // 正在录音
- rlRecording.setVisibility(View.VISIBLE);
- // 播放动画
- animationDrawable.start();
- ivCancel.setVisibility(View.GONE);
- ivTooShort.setVisibility(View.GONE);
- tvState.setText(getString(R.string.slideup_to_cancel));
- break;
- case CANCELED: // 取消录音
- rlRecording.setVisibility(View.GONE);
- // 停止动画
- if (animationDrawable.isRunning()) {
- animationDrawable.stop();
- }
- ivCancel.setVisibility(View.VISIBLE);
- ivTooShort.setVisibility(View.GONE);
- tvState.setText(getString(R.string.loose_to_cancel));
- break;
- case TOO_SHORT:// 录音时间太短
- rlRecording.setVisibility(View.GONE);
- // 停止动画
- if (animationDrawable.isRunning()) {
- animationDrawable.stop();
- }
- ivCancel.setVisibility(View.GONE);
- ivTooShort.setVisibility(View.VISIBLE);
- tvState.setText(getString(R.string.record_too_short));
- break;
- }
- }
- mRecordPopupWindow.showAtLocation(mRecyclerView, Gravity.CENTER, 0, 0);
- }
- @OnClick({R.id.chat_send_msg, R.id.chat_intercept})
- public void onClick(View view) {
- switch (view.getId()) {
- case R.id.chat_send_msg:// 发送文字消息
- mBtnSend.setEnabled(true);
- sendTextMessage();
- break;
- case R.id.chat_intercept:// 支付拦截
- //添加好评送会员
- if (mIsShowSendVipByPraise) {
- ActionSheetDialogNoTitle();
- } else {
- BuyServiceActivity.toBuyServiceActivity(ChatActivity.this, BuyServiceActivity.INTENT_FROM_INTERCEPT,
- IConfigConstant.PAY_TAG_FROM_CHAT, IConfigConstant.PAY_WAY_ALL);
- }
- break;
- }
- }
- private void ActionSheetDialogNoTitle() {
- final String[] stringItems = {getString(R.string.free_use), getString(R.string.buy_vip_service)};
- final ActionSheetDialog dialog = new ActionSheetDialog(ChatActivity.this, stringItems, mTvIntercept);
- dialog.isTitleShow(false).show();
- dialog.setOnOperItemClickL(new OnOperItemClickL() {
- @Override
- public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
- if (position == 0) {
- DialogUtil.showDoubleBtnDialog(getSupportFragmentManager(), getString(R.string.hour12_vip), getString(R.string.send_vip), getString(R.string.go_good), getString(R.string.cancel), false, new OnDoubleDialogClickListener() {
- @Override
- public void onPositiveClick(View view) {
- Intent intent = new Intent();
- intent.setAction(Intent.ACTION_VIEW);
- intent.setData(Uri.parse("market://details?id=" + VersionInfoUtil.getPackageName(ChatActivity.this)));
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- if (VersionInfoUtil.checkAPKExist(ChatActivity.this, "com.android.vending")) {
- // 直接跳转Google商店
- intent.setPackage("com.android.vending");
- }
- startActivity(intent);
- }
- @Override
- public void onNegativeClick(View view) {
- }
- });
- } else if (position == 1) {
- BuyServiceActivity.toBuyServiceActivity(ChatActivity.this, BuyServiceActivity.INTENT_FROM_INTERCEPT,
- IConfigConstant.PAY_TAG_FROM_CHAT, IConfigConstant.PAY_WAY_ALL);
- }
- dialog.dismiss();
- }
- });
- }
- private void loadMsgList() {
- OkHttpUtils.post()
- .url(IUrlConstant.URL_GET_CHAT_MSG)
- .addHeader("token", PlatformInfoXml.getToken())
- .addParams("platformInfo", PlatformInfoXml.getPlatformJsonString())
- .addParams("uid", mUserId)
- .build()
- .execute(new Callback<MessageList>() {
- @Override
- public MessageList parseNetworkResponse(Response response, int id) throws Exception {
- String resultJson = response.body().string();
- if (!TextUtils.isEmpty(resultJson)) {
- return JSON.parseObject(resultJson, MessageList.class);
- }
- return null;
- }
- @Override
- public void onError(Call call, Exception e, int id) {
- stopRefresh(3);
- }
- @Override
- public void onResponse(MessageList response, int id) {
- if (response != null) {
- // 设置支付拦截
- String intercept = response.getShowWriteMsgIntercept();
- if (!TextUtils.isEmpty(intercept) && "1".equals(intercept)) {
- // 展示拦截入口
- mIsShowWriteMsgIntercept = true;
- mTvIntercept.setVisibility(View.VISIBLE);
- mRlChatContainer.setVisibility(View.GONE);
- // SharedPreferenceUtil.setBooleanValue(Utils.getContext(), "INTERCEPT_DIALOG", "DIALOG", true);
- } else {// 不展示拦截入口
- mIsShowWriteMsgIntercept = false;
- mTvIntercept.setVisibility(View.GONE);
- mRlChatContainer.setVisibility(View.VISIBLE);
- // SharedPreferenceUtil.setBooleanValue(Utils.getContext(), "INTERCEPT_DIALOG", "DIALOG", false);
- }
- mRlChatBottom.setVisibility(View.VISIBLE);
- String isSucceed = response.getIsSucceed();
- if (!TextUtils.isEmpty(isSucceed) && "1".equals(isSucceed)) {
- if (mChatAdapter != null) {
- mChatAdapter.setAvatarUrl(mAvatarUrl);
- mChatAdapter.setServerSystemTime(response.getSystemTime());
- mChatAdapter.isIntercept(mIsShowWriteMsgIntercept);
- mChatAdapter.isShowVoiceLoading(false);
- mChatAdapter.isShowVoiceRetry(false);
- mChatAdapter.isShowImgLoading(false);
- mChatAdapter.isShowImgRetry(false);
- List<Message> messageList = response.getListMsg();
- if (!Util.isListEmpty(messageList)) {
- List<Image> imageList = new ArrayList<Image>();
- for (Message message : messageList) {
- if (message != null) {
- Image image = message.getChatImage();
- if (image != null) {
- imageList.add(image);
- }
- }
- }
- mChatAdapter.setAllImageList(imageList);
- mChatAdapter.replaceAll(messageList);
- // 滚动到底部
- mLinearLayoutManager.scrollToPosition(mLinearLayoutManager.getItemCount() - 1);
- }
- }
- }
- // 设置五星好评
- if (response.getIsShowSendVipByPraise() != null && response.getIsShowSendVipByPraise().equals("1")) {
- mIsShowSendVipByPraise = true;
- } else {
- mIsShowSendVipByPraise = false;
- }
- }
- stopRefresh(1);
- }
- });
- }
- private void stopRefresh(int secs) {
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- if (mAutoSwipeRefresh != null) {
- mAutoSwipeRefresh.setRefreshing(false);
- }
- }
- }, secs * 1000);
- }
- /**
- * 发送文字消息
- */
- private void sendTextMessage() {
- OkHttpUtils.post()
- .url(IUrlConstant.URL_SEND_TEXT_MSG)
- .addHeader("token", PlatformInfoXml.getToken())
- .addParams("platformInfo", PlatformInfoXml.getPlatformJsonString())
- .addParams("uid", mUserId)
- .addParams("writeMsgType", "1")
- .addParams("content", mEtInput.getText().toString().trim())
- .build()
- .execute(new Callback<WriteMsg>() {
- @Override
- public WriteMsg parseNetworkResponse(Response response, int id) throws Exception {
- String resultJson = response.body().string();
- if (!TextUtils.isEmpty(resultJson)) {
- return JSON.parseObject(resultJson, WriteMsg.class);
- }
- mBtnSend.setEnabled(true);
- return null;
- }
- @Override
- public void onError(Call call, Exception e, int id) {
- ToastUtil.showShortToast(ChatActivity.this, getString(R.string.send_fail));
- mBtnSend.setEnabled(true);
- }
- @Override
- public void onResponse(WriteMsg response, int id) {
- if (response != null) {
- String isSucceed = response.getIsSucceed();
- if (!TextUtils.isEmpty(isSucceed) && "1".equals(isSucceed)) {
- // 重置状态
- mEtInput.setText("");
- loadMsgList();
- // 发送事件,更新聊天列表
- EventBus.getDefault().post(new MessageChangedEvent());
- } else {
- ToastUtil.showShortToast(ChatActivity.this, getString(R.string.send_fail));
- }
- } else {
- ToastUtil.showShortToast(ChatActivity.this, getString(R.string.send_fail));
- }
- }
- });
- }
- /**
- * 发送语音消息
- */
- private void sendVoiceMsg() {
- // 发送语音前显示要发送的图片进度
- final Message message = new Message();
- if (mChatAdapter != null) {
- mChatAdapter.isShowVoiceLoading(true);
- mChatAdapter.isShowVoiceRetry(false);
- message.setUid(UserInfoXml.getUID());
- message.setMsgType("7");
- message.setCreateDateMills(System.currentTimeMillis());
- message.setRecevStatus("1");
- message.setAudioTime(String.valueOf(Math.round(mRecordDuration / 1000)));
- message.setAudioUrl(mOutputPath);
- mChatAdapter.insertItem(mChatAdapter.getItemCount(), message);
- // 滚动到底部
- mLinearLayoutManager.scrollToPosition(mChatAdapter.getItemCount() - 1);
- }
- OkHttpUtils.post()
- .url(IUrlConstant.URL_SEND_VOICE_MSG)
- .addHeader("token", PlatformInfoXml.getToken())
- .addHeader("platformInfo", PlatformInfoXml.getPlatformJsonString())
- .addHeader("uid", mUserId)
- .addHeader("writeMsgType", "1")
- .addHeader("audioSecond", String.valueOf(Math.round(mRecordDuration / 1000)))
- .addFile("file", mRecordFileName, new File(mOutputPath))
- .build()
- .execute(new Callback<BaseModel>() {
- @Override
- public BaseModel parseNetworkResponse(Response response, int id) throws Exception {
- String resultJson = response.body().string();
- if (!TextUtils.isEmpty(resultJson)) {
- return JSON.parseObject(resultJson, BaseModel.class);
- }
- return null;
- }
- @Override
- public void onError(Call call, Exception e, int id) {
- sendVoiceFailed(message);
- }
- @Override
- public void onResponse(BaseModel response, int id) {
- if (response != null) {
- String isSucceed = response.getIsSucceed();
- if (!TextUtils.isEmpty(isSucceed) && "1".equals(isSucceed)) {
- loadMsgList();
- // 发送事件,更新聊天列表
- EventBus.getDefault().post(new MessageChangedEvent());
- } else {
- sendVoiceFailed(message);
- }
- } else {
- sendVoiceFailed(message);
- }
- }
- });
- }
- /**
- * 发送语音失败,刷新状态
- */
- private void sendVoiceFailed(Message message) {
- mChatAdapter.isShowVoiceLoading(false);
- mChatAdapter.isShowVoiceRetry(true);
- mChatAdapter.updateItem(mChatAdapter.getItemCount() - 1, message);
- ToastUtil.showShortToast(ChatActivity.this, getString(R.string.send_fail));
- }
- /**
- * 发送图片消息
- */
- private void sendPhotoMsg(File file, final Message message) {
- OkHttpUtils.post()
- .url(IUrlConstant.URL_SEND_PHOTO_MSG)
- .addHeader("token", PlatformInfoXml.getToken())
- .addHeader("platformInfo", PlatformInfoXml.getPlatformJsonString())
- .addHeader("recevUserId", mUserId)
- .addFile("request", file.getName(), file)
- .build()
- .execute(new Callback<BaseModel>() {
- @Override
- public BaseModel parseNetworkResponse(Response response, int id) throws Exception {
- String resultJson = response.body().string();
- if (!TextUtils.isEmpty(resultJson)) {
- return JSON.parseObject(resultJson, BaseModel.class);
- }
- return null;
- }
- @Override
- public void onError(Call call, Exception e, int id) {
- sendPhotoFailed(message);
- }
- @Override
- public void onResponse(BaseModel response, int id) {
- if (response != null) {
- String isSucceed = response.getIsSucceed();
- if (!TextUtils.isEmpty(isSucceed) && "1".equals(isSucceed)) {
- loadMsgList();
- // 发送事件,更新聊天列表
- EventBus.getDefault().post(new MessageChangedEvent());
- } else {
- sendPhotoFailed(message);
- }
- } else {
- sendPhotoFailed(message);
- }
- }
- });
- }
- /**
- * 发送图片失败,刷新状态
- */
- private void sendPhotoFailed(Message message) {
- mChatAdapter.isShowImgLoading(false);
- mChatAdapter.isShowImgRetry(true);
- mChatAdapter.updateItem(mChatAdapter.getItemCount() - 1, message);
- ToastUtil.showShortToast(ChatActivity.this, getString(R.string.send_fail));
- }
- @Override
- protected void doRegister() {
- super.doRegister();
- EventBus.getDefault().register(this);
- }
- @Override
- protected void unregister() {
- super.unregister();
- EventBus.getDefault().unregister(this);
- // 释放录音和播放器资源
- RecordUtil.getInstance().releaseRecord();
- if (RecordUtil.getInstance().isPlaying()) {// 如果正在播放语音,需要停止
- RecordUtil.getInstance().stop();
- }
- RecordUtil.getInstance().release();
- }
- @Subscribe
- public void onEvent(RefreshChatEvent event) {
- loadMsgList();
- }
- }
- ///**
- // * 聊天页面
- // * Created by zhangdroid on 2016/11/2.
- // */
- //public class ChatActivity extends BaseTitleActivity {
- // @BindView(R.id.chat_swiperefresh)
- // AutoSwipeRefreshLayout mAutoSwipeRefresh;
- // @BindView(R.id.chat_RecyclerView)
- // RecyclerView mRecyclerView;
- // @BindView(R.id.chat_bottom_bar)
- // RelativeLayout mRlChatBottom;
- // @BindView(R.id.chat_operate_container)
- // RelativeLayout mRlChatContainer;
- // @BindView(R.id.chat_et_input)
- // ClearableEditText mEtInput;
- // @BindView(R.id.chat_send_msg)
- // Button mBtnSend;// 发送文字消息
- // @BindView(R.id.chat_send_photo)
- // ImageView mIvSendPhoto;// 发送图片
- // @BindView(R.id.chat_intercept)
- // TextView mTvIntercept;
- // // 语音
- // @BindView(R.id.chat_msg_switch)
- // ImageView mIvChatSwitch;
- // @BindView(R.id.record)
- // Button mBtnRecord;
- //
- // /**
- // * 用户id
- // */
- // private String mUserId;
- // /**
- // * 用户昵称
- // */
- // private String mNickname;
- // /**
- // * 用户头像url
- // */
- // private String mAvatarUrl;
- //
- // private ChatAdapter mChatAdapter;
- // private LinearLayoutManager mLinearLayoutManager;
- // // 录音框
- // private PopupWindow mRecordPopupWindow;
- // private static final int PERMISSION_CODE_RECORD_AUDIO = 0;
- // private static final int PERMISSION_CODE_WRITE_EXTERNAL_STORAGE = 1;
- // private static final int MSG_TYPE_TIMER = 1;
- //
- // // 录音文件路径
- // private String mOutputPath;
- // // 录音文件名
- // private String mRecordFileName;
- // // 是否正在录音
- // private boolean mIsRecording;
- // // 录音是否被取消
- // private boolean mIsRecordCanceled;
- // // 录音时长(毫秒)
- // private long mRecordDuration;
- // // 录音计时刷新间隔(毫秒)
- // private final long mRefreshInterval = 250;
- // // 计算录音时长的Handler
- // private Handler mTimerHandler = new Handler() {
- //
- // @Override
- // public void handleMessage(android.os.Message msg) {
- // super.handleMessage(msg);
- // switch (msg.what) {
- // case MSG_TYPE_TIMER:
- // if (mIsRecording) {
- // // 计时
- // mRecordDuration += mRefreshInterval;
- // // 录音超过1分钟自动发送
- // if (mRecordDuration > 60 * 1000) {
- // stopRecordAndSend();
- // } else {
- // mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_TIMER, mRefreshInterval);
- // }
- // }
- // break;
- // }
- // }
- // };
- //
- // // 录音状态常量
- // private enum STATE {
- // /**
- // * 默认值
- // */
- // IDLE,
- // /**
- // * 录音中
- // */
- // RECORDING,
- // /**
- // * 取消
- // */
- // CANCELED,
- // /**
- // * 录音时间太短
- // */
- // TOO_SHORT
- // }
- //
- // private boolean mIsShowSendVipByPraise = false;
- // private boolean mIsShowWriteMsgIntercept = false;
- //
- // private static final String INTENT_KEY_UID = "key_userId";
- // private static final String INTENT_KEY_NICKNAME = "key_nickname";
- // private static final String INTENT_KEY_AVATAR_URL = "key_avatar_url";
- // private static final String INTENT_KEY_NEED_REFRESH = "key_need_refresh";
- //
- // /**
- // * 跳转聊天页
- // *
- // * @param from
- // * @param userId 用户id
- // * @param nickname 用户昵称
- // * @param avatarUrl 用户头像url
- // */
- // public static void toChatActivity(Activity from, String userId, String nickname, String avatarUrl) {
- // Map<String, String> map = new HashMap<String, String>();
- // map.put(INTENT_KEY_UID, userId);
- // map.put(INTENT_KEY_NICKNAME, nickname);
- // map.put(INTENT_KEY_AVATAR_URL, avatarUrl);
- // Util.gotoActivity(from, ChatActivity.class, false, map);
- // }
- //
- // /**
- // * 跳转聊天页
- // *
- // * @param context
- // * @param userId 用户id
- // * @param nickname 用户昵称
- // * @param avatarUrl 用户头像url
- // */
- // public static void toChatActivity(Context context, String userId, String nickname, String avatarUrl) {
- // Intent intent = new Intent(context, ChatActivity.class);
- // intent.putExtra(INTENT_KEY_UID, userId);
- // intent.putExtra(INTENT_KEY_NICKNAME, nickname);
- // intent.putExtra(INTENT_KEY_AVATAR_URL, avatarUrl);
- // context.startActivity(intent);
- // }
- //
- // // 数据库相关
- // private MessageDao mMessageDao;
- // private MyHandler mMyHandler;
- //
- // private static final int MSG_TYPE_DB = 0;
- // private static final int MSG_TYPE_NET = 1;
- //
- // private static class MyHandler extends Handler {
- // private WeakReference<ChatActivity> mChatActivity;
- //
- // public MyHandler(ChatActivity chatActivity) {
- // this.mChatActivity = new WeakReference<ChatActivity>(chatActivity);
- // }
- //
- // @Override
- // public void handleMessage(android.os.Message msg) {
- // super.handleMessage(msg);
- // final ChatActivity chatActivity = mChatActivity.get();
- // switch (msg.what) {
- // case MSG_TYPE_DB:
- // LogUtil.e(LogUtil.TAG_ZL, "load chat history from db.");
- // if (chatActivity != null) {
- // chatActivity.setAdapterData((List<Message>) msg.obj);
- // chatActivity.stopRefresh(1);
- // }
- // break;
- //
- // case MSG_TYPE_NET:
- // LogUtil.e(LogUtil.TAG_ZL, "load chat history from net.");
- // if (chatActivity != null) {
- // chatActivity.loadMsgList();
- // }
- // break;
- // }
- // }
- // }
- //
- // @Override
- // protected int getLayoutResId() {
- // return R.layout.activity_chat;
- // }
- //
- // @Override
- // protected String getCenterTitle() {
- // return null;
- // }
- //
- // @Override
- // protected void initViewsAndVariables() {
- // Intent intent = getIntent();
- // if (intent != null) {
- // mUserId = intent.getStringExtra(INTENT_KEY_UID);
- // mNickname = intent.getStringExtra(INTENT_KEY_NICKNAME);
- // mAvatarUrl = intent.getStringExtra(INTENT_KEY_AVATAR_URL);
- // }
- // if (!TextUtils.isEmpty(mNickname)) {
- // setTitle(mNickname);
- // }
- //
- // // 设置下拉刷新动画样式
- // mAutoSwipeRefresh.setColorSchemeResources(R.color.main_color);
- // mAutoSwipeRefresh.setProgressBackgroundColorSchemeColor(Color.WHITE);
- // mLinearLayoutManager = new LinearLayoutManager(this);
- // mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
- // mRecyclerView.setLayoutManager(mLinearLayoutManager);
- // mChatAdapter = new ChatAdapter(this, -1);
- // mChatAdapter.setUserId(mUserId);
- // mChatAdapter.setAvatarUrl(mAvatarUrl);
- // mRecyclerView.setAdapter(mChatAdapter);
- //
- // // 获得数据库操作对象
- // mMessageDao = GreenDaoUtil.getDaoSession().getMessageDao();
- // mMyHandler = new MyHandler(this);
- // }
- //
- // /**
- // * 先从本地数据库查询,若没有则从网络获取
- // */
- // private void loadChatHistory() {
- // new Thread(new Runnable() {
- // @Override
- // public void run() {
- // // 查询与当前用户的所有聊天记录
- // QueryBuilder queryBuilder = mMessageDao.queryBuilder();
- // queryBuilder.where(MessageDao.Properties.Uid.eq(mUserId), MessageDao.Properties.RecevUserId.eq(UserInfoXml.getUID()))
- // .or(MessageDao.Properties.Uid.eq(UserInfoXml.getUID()), MessageDao.Properties.RecevUserId.eq(mUserId));
- // List<Message> dbList = queryBuilder.list();
- // if (!Util.isListEmpty(dbList)) {
- // // 数据库中存在聊天记录,直接显示
- // android.os.Message message = android.os.Message.obtain();
- // message.what = MSG_TYPE_DB;
- // message.obj = dbList;
- // mMyHandler.sendMessage(message);
- // } else {
- // // 否则从网络加载
- // mMyHandler.sendEmptyMessage(MSG_TYPE_NET);
- // }
- // }
- // }).start();
- // }
- //
- // /**
- // * 从网络加载聊天记录
- // */
- // private void loadMsgList() {
- // OkHttpUtils.post()
- // .url(IUrlConstant.URL_GET_CHAT_MSG)
- // .addHeader("token", PlatformInfoXml.getToken())
- // .addParams("platformInfo", PlatformInfoXml.getPlatformJsonString())
- // .addParams("uid", mUserId)
- // .addParams("startTime", "")
- // .build()
- // .execute(new Callback<MessageList>() {
- //
- // @Override
- // public MessageList parseNetworkResponse(Response response, int id) throws Exception {
- // String resultJson = response.body().string();
- // if (!TextUtils.isEmpty(resultJson)) {
- // return JSON.parseObject(resultJson, MessageList.class);
- // }
- // return null;
- // }
- //
- // @Override
- // public void onError(Call call, Exception e, int id) {
- // stopRefresh(3);
- // }
- //
- // @Override
- // public void onResponse(MessageList response, int id) {
- // if (response != null) {
- // // 设置支付拦截
- // String intercept = response.getShowWriteMsgIntercept();
- // if (!TextUtils.isEmpty(intercept) && "1".equals(intercept)) {
- // // 展示拦截入口
- // mIsShowWriteMsgIntercept = true;
- // mTvIntercept.setVisibility(View.VISIBLE);
- // mRlChatContainer.setVisibility(View.GONE);
- // } else {// 不展示拦截入口
- // mIsShowWriteMsgIntercept = false;
- // mTvIntercept.setVisibility(View.GONE);
- // mRlChatContainer.setVisibility(View.VISIBLE);
- // }
- // // 设置五星好评
- // mIsShowSendVipByPraise = response.getIsShowSendVipByPraise() != null && response.getIsShowSendVipByPraise().equals("1");
- // // 更新聊天列表并存入数据库
- // String isSucceed = response.getIsSucceed();
- // if (!TextUtils.isEmpty(isSucceed) && "1".equals(isSucceed)) {
- // List<Message> messageList = response.getListMsg();
- // if (!Util.isListEmpty(messageList)) {
- // setAdapterData(messageList);
- // insert(messageList);
- // }
- // }
- // }
- // stopRefresh(1);
- // }
- // });
- // }
- //
- // /**
- // * 向数据库中插入新增的聊天记录
- // *
- // * @param messageList
- // */
- // private void insert(final List<Message> messageList) {
- // new Thread(new Runnable() {
- // @Override
- // public void run() {
- // // 批量插入
- // mMessageDao.insertOrReplaceInTx(messageList);
- // }
- // }).start();
- // }
- //
- // private void setAdapterData(List<Message> messageList) {
- // if (mChatAdapter != null && !Util.isListEmpty(messageList)) {
- // // 查找聊天记录中所有图片
- // List<Image> imageList = new ArrayList<Image>();
- // for (Message message : messageList) {
- // if (message != null) {
- // Image image = message.getChatImage();
- // if (image != null) {
- // imageList.add(image);
- // }
- // }
- // }
- // mChatAdapter.setAllImageList(imageList);
- // mChatAdapter.replaceAll(messageList);
- // // 滚动到底部
- // mLinearLayoutManager.scrollToPosition(mLinearLayoutManager.getItemCount() - 1);
- // }
- // }
- //
- // private void stopRefresh(int secs) {
- // new Handler().postDelayed(new Runnable() {
- // @Override
- // public void run() {
- // if (mAutoSwipeRefresh != null) {
- // mAutoSwipeRefresh.setRefreshing(false);
- // }
- // }
- // }, secs * 1000);
- // }
- //
- // @Override
- // protected void addListeners() {
- // mAutoSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
- // @Override
- // public void onRefresh() {
- // loadChatHistory();
- // }
- // });
- // // 处理滑动冲突
- // mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
- // @Override
- // public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
- // super.onScrollStateChanged(recyclerView, newState);
- // }
- //
- // @Override
- // public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
- // super.onScrolled(recyclerView, dx, dy);
- // // 判断是否滑动到顶部
- // int scrolledPosition = (mRecyclerView == null || mRecyclerView.getChildCount() == 0) ? 0 : mRecyclerView.getChildAt(0).getTop();
- // mAutoSwipeRefresh.setEnabled(scrolledPosition >= 0);
- // }
- // });
- // // 发送文字消息
- // mEtInput.setTextWatcherCallback(new ClearableEditText.TextWatcherCallback() {
- //
- // @Override
- // public void handleTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
- // if (mEtInput.length() > 0) {
- // mBtnSend.setVisibility(View.VISIBLE);
- // mIvSendPhoto.setVisibility(View.GONE);
- // } else {
- // mBtnSend.setVisibility(View.GONE);
- // mIvSendPhoto.setVisibility(View.VISIBLE);
- // }
- // }
- // });
- // // 切换文字/语音
- // mIvChatSwitch.setOnClickListener(new View.OnClickListener() {
- // @Override
- // public void onClick(View v) {
- // mIvChatSwitch.setSelected(!mIvChatSwitch.isSelected());
- // if (mIvChatSwitch.isSelected()) { // 显示发送语音
- // mBtnRecord.setText(getString(R.string.press_to_speak));
- // mBtnRecord.setVisibility(View.VISIBLE);
- // mEtInput.setVisibility(View.GONE);
- // mBtnSend.setVisibility(View.GONE);
- // mIvSendPhoto.setVisibility(View.GONE);
- // if (mIsShowWriteMsgIntercept) {// 支付拦截时不可用
- // mBtnRecord.setClickable(false);
- // mBtnRecord.setEnabled(false);
- // mBtnRecord.setTextColor(getResources().getColor(R.color.textcolor_light_gray));
- // } else {
- // mBtnRecord.setClickable(true);
- // mBtnRecord.setEnabled(true);
- // mBtnRecord.setTextColor(getResources().getColor(R.color.main_color));
- // }
- // } else { // 显示输入框
- // mBtnRecord.setVisibility(View.GONE);
- // mEtInput.setVisibility(View.VISIBLE);
- // if (mEtInput.getText().length() > 0) {
- // // 已经输入文字
- // mBtnSend.setVisibility(View.VISIBLE);
- // mIvSendPhoto.setVisibility(View.GONE);
- // } else {
- // mBtnSend.setVisibility(View.GONE);
- // mIvSendPhoto.setVisibility(View.VISIBLE);
- // }
- // }
- // }
- // });
- // // 发送语音消息
- // mBtnRecord.setOnTouchListener(new View.OnTouchListener() {
- // @Override
- // public boolean onTouch(View v, MotionEvent event) {
- // // 检查权限
- // if (!checkPermissions()) {// 请求权限时不录音
- // switch (event.getAction()) {
- // case MotionEvent.ACTION_DOWN:// 按下时开始录音
- // mBtnRecord.setText(getString(R.string.loose_to_end));
- // showRecordPopupWindow(STATE.RECORDING);
- // startRecord();
- // mIsRecordCanceled = false;
- // LogUtil.e(LogUtil.TAG_ZL, "ACTION_DOWN start()");
- // break;
- //
- // case MotionEvent.ACTION_MOVE:
- // if (event.getY() < -100) { // 上滑取消发送
- // mIsRecordCanceled = true;
- // showRecordPopupWindow(STATE.CANCELED);
- // } else {
- // mIsRecordCanceled = false;
- // showRecordPopupWindow(STATE.RECORDING);
- // }
- // LogUtil.e(LogUtil.TAG_ZL, "ACTION_MOVE " + event.getY() + " mIsRecordCanceled = " + mIsRecordCanceled);
- // break;
- //
- // case MotionEvent.ACTION_UP:// 松开时停止录音并发送
- // mBtnRecord.setText(getString(R.string.press_to_speak));
- // if (mIsRecordCanceled) {
- // cancelRecord();
- // LogUtil.e(LogUtil.TAG_ZL, "ACTION_UP canceld()");
- // } else {
- // stopRecordAndSend();
- // LogUtil.e(LogUtil.TAG_ZL, "ACTION_UP stop()");
- // }
- // break;
- // }
- // }
- // return true;
- // }
- // });
- // // 发送图片
- // mIvSendPhoto.setOnClickListener(new View.OnClickListener() {
- // @Override
- // public void onClick(View v) {
- // GetPhotoActivity.toGetPhotoActivity(ChatActivity.this, IConfigConstant.LOCAL_PIC_PATH, new GetPhotoActivity.OnGetPhotoListener() {
- // @Override
- // public void getSelectedPhoto(File file) {
- // if (file != null) {
- // // 发送图片前显示要发送的图片进度
- // Message message = new Message();
- // if (mChatAdapter != null) {
- // mChatAdapter.isShowImgLoading(true);
- // mChatAdapter.isShowImgRetry(false);
- // message.setUid(UserInfoXml.getUID());
- // message.setMsgType("10");
- // message.setCreateDateMills(System.currentTimeMillis());
- // Image image = new Image();
- // image.setIsMain(2);
- // image.setThumbnailUrl(file.getAbsolutePath());
- // image.setThumbnailUrlM(file.getAbsolutePath());
- // image.setImageUrl(file.getAbsolutePath());
- // message.setChatImage(image);
- // mChatAdapter.insertItem(mChatAdapter.getItemCount(), message);
- // // 滚动到底部
- // mLinearLayoutManager.scrollToPosition(mChatAdapter.getItemCount() - 1);
- // }
- // sendPhotoMsg(file, message);
- // }
- // }
- // });
- // }
- // });
- // }
- //
- // private boolean checkPermissions() {
- // boolean needRequestPermission = false;
- // if (ContextCompat.checkSelfPermission(ChatActivity.this.getApplicationContext(),
- // Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_DENIED) {
- // needRequestPermission = true;
- // // 请求android.permission.RECORD_AUDIO权限
- // ActivityCompat.requestPermissions(ChatActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSION_CODE_RECORD_AUDIO);
- // }
- // if (ContextCompat.checkSelfPermission(ChatActivity.this.getApplicationContext(),
- // Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
- // needRequestPermission = true;
- // // 请求android.permission.WRITE_EXTERNAL_STORAGE权限
- // ActivityCompat.requestPermissions(ChatActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CODE_WRITE_EXTERNAL_STORAGE);
- // }
- // return needRequestPermission;
- // }
- //
- // @Override
- // public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- // super.onRequestPermissionsResult(requestCode, permissions, grantResults);
- // }
- //
- // /**
- // * 开始录音
- // */
- // private void startRecord() {
- // // 录音开始前震动一下
- // Vibrator vibrator = (Vibrator) ChatActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
- // vibrator.vibrate(88);
- // // 根据系统时间生成文件名
- // mRecordFileName = FileUtil.createFileNameByTime() + ".mp3";
- // // 录音文件保存路径: 根目录/DateLove/record/用户id/xxx.mp3
- // mOutputPath = FileUtil.RECORD_DIRECTORY_PATH + File.separator + UserInfoXml.getUID() + File.separator + mRecordFileName;
- // LogUtil.e(LogUtil.TAG_ZL, "录音存放路径:" + mOutputPath);
- // // 开始录音
- // RecordUtil.getInstance().startRecord(mOutputPath);
- // mIsRecording = true;
- // mRecordDuration = 0;
- // // 计时,间隔250毫秒刷新
- // mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_TIMER, mRefreshInterval);
- // }
- //
- // /**
- // * 停止录音并发送
- // */
- // private void stopRecordAndSend() {
- // if (mIsRecording) {
- // mIsRecording = false;
- // LogUtil.e(LogUtil.TAG_ZL, "录音时长(毫秒):" + mRecordDuration);
- // if (mRecordDuration < 1 * 1000) {// 录音时长小于1秒的不发送
- // showRecordPopupWindow(STATE.TOO_SHORT);
- // new Handler().postDelayed(new Runnable() {
- // @Override
- // public void run() {
- // // 延时500毫秒调用MediaRecorder#stop(),防止出现start()之后立马调用stop()的异常
- // RecordUtil.getInstance().stopRecord();
- // // 删除小于1秒的文件
- // FileUtil.deleteFile(mOutputPath);
- // }
- // }, 500);
- // } else {// 发送语音
- // RecordUtil.getInstance().stopRecord();
- // sendVoiceMsg();
- // }
- // // 隐藏录音框
- // new Handler().postDelayed(new Runnable() {
- // @Override
- // public void run() {
- // if (mRecordPopupWindow != null && mRecordPopupWindow.isShowing()) {
- // mRecordPopupWindow.dismiss();
- // }
- // }
- // }, 500);
- // }
- // }
- //
- // /**
- // * 录音取消,删除已经录制的文件
- // */
- // private void cancelRecord() {
- // if (mIsRecordCanceled) {
- // RecordUtil.getInstance().stopRecord();
- // mIsRecordCanceled = false;
- // FileUtil.deleteFile(mOutputPath);
- //
- // // 隐藏录音框
- // new Handler().postDelayed(new Runnable() {
- // @Override
- // public void run() {
- // if (mRecordPopupWindow != null && mRecordPopupWindow.isShowing()) {
- // mRecordPopupWindow.dismiss();
- // }
- // }
- // }, 500);
- // }
- // }
- //
- // /**
- // * 弹出录音框
- // */
- // private void showRecordPopupWindow(STATE state) {
- // if (mRecordPopupWindow == null) {
- // View contentView = LayoutInflater.from(ChatActivity.this).inflate(R.layout.popup_chat_record, null);
- // mRecordPopupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.WRAP_CONTENT,
- // WindowManager.LayoutParams.WRAP_CONTENT, true);
- // mRecordPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
- // }
- //
- // View view = mRecordPopupWindow.getContentView();
- // if (view != null) {
- // RelativeLayout rlRecording = (RelativeLayout) view.findViewById(R.id.popup_recording_container);
- // ImageView ivRecording = (ImageView) view.findViewById(R.id.popup_record_anim);
- // // 设置动画
- // List<Drawable> drawableList = new ArrayList<Drawable>();
- // drawableList.add(getResources().getDrawable(R.drawable.voice1));
- // drawableList.add(getResources().getDrawable(R.drawable.voice2));
- // drawableList.add(getResources().getDrawable(R.drawable.voice3));
- // drawableList.add(getResources().getDrawable(R.drawable.voice4));
- // drawableList.add(getResources().getDrawable(R.drawable.voice5));
- // drawableList.add(getResources().getDrawable(R.drawable.voice6));
- // AnimationDrawable animationDrawable = Utils.getFrameAnim(drawableList, true, 150);
- // ivRecording.setImageDrawable(animationDrawable);
- //
- // ImageView ivCancel = (ImageView) view.findViewById(R.id.popup_cancel_record);
- // ImageView ivTooShort = (ImageView) view.findViewById(R.id.popup_record_too_short);
- // TextView tvState = (TextView) view.findViewById(R.id.popup_record_state);
- // switch (state) {
- // case RECORDING: // 正在录音
- // rlRecording.setVisibility(View.VISIBLE);
- // // 播放动画
- // animationDrawable.start();
- // ivCancel.setVisibility(View.GONE);
- // ivTooShort.setVisibility(View.GONE);
- // tvState.setText(getString(R.string.slideup_to_cancel));
- // break;
- //
- // case CANCELED: // 取消录音
- // rlRecording.setVisibility(View.GONE);
- // // 停止动画
- // if (animationDrawable.isRunning()) {
- // animationDrawable.stop();
- // }
- // ivCancel.setVisibility(View.VISIBLE);
- // ivTooShort.setVisibility(View.GONE);
- // tvState.setText(getString(R.string.loose_to_cancel));
- // break;
- //
- // case TOO_SHORT:// 录音时间太短
- // rlRecording.setVisibility(View.GONE);
- // // 停止动画
- // if (animationDrawable.isRunning()) {
- // animationDrawable.stop();
- // }
- // ivCancel.setVisibility(View.GONE);
- // ivTooShort.setVisibility(View.VISIBLE);
- // tvState.setText(getString(R.string.record_too_short));
- // break;
- // }
- // }
- // mRecordPopupWindow.showAtLocation(mRecyclerView, Gravity.CENTER, 0, 0);
- // }
- //
- // @OnClick({R.id.chat_send_msg, R.id.chat_intercept})
- // public void onClick(View view) {
- // switch (view.getId()) {
- // case R.id.chat_send_msg:// 发送文字消息
- // mBtnSend.setEnabled(false);
- // sendTextMessage();
- // break;
- //
- // case R.id.chat_intercept:// 支付拦截
- // //添加好评送会员
- // if (mIsShowSendVipByPraise) {
- // ActionSheetDialogNoTitle();
- // } else {
- // BuyServiceActivity.toBuyServiceActivity(ChatActivity.this, BuyServiceActivity.INTENT_FROM_INTERCEPT,
- // IConfigConstant.PAY_TAG_FROM_CHAT, IConfigConstant.PAY_WAY_ALL);
- // }
- // break;
- // }
- // }
- //
- // private void ActionSheetDialogNoTitle() {
- // final String[] stringItems = {getString(R.string.free_use), getString(R.string.buy_vip_service)};
- // final ActionSheetDialog dialog = new ActionSheetDialog(ChatActivity.this, stringItems, mTvIntercept);
- // dialog.isTitleShow(false).show();
- //
- // dialog.setOnOperItemClickL(new OnOperItemClickL() {
- // @Override
- // public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
- // if (position == 0) {
- // DialogUtil.showDoubleBtnDialog(getSupportFragmentManager(), getString(R.string.hour12_vip), getString(R.string.send_vip), getString(R.string.go_good), getString(R.string.cancel), false, new OnDoubleDialogClickListener() {
- // @Override
- // public void onPositiveClick(View view) {
- // Intent intent = new Intent();
- // intent.setAction(Intent.ACTION_VIEW);
- // intent.setData(Uri.parse("market://details?id=" + VersionInfoUtil.getPackageName(ChatActivity.this)));
- // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- // if (VersionInfoUtil.checkAPKExist(ChatActivity.this, "com.android.vending")) {
- // // 直接跳转Google商店
- // intent.setPackage("com.android.vending");
- // }
- // startActivity(intent);
- // }
- //
- // @Override
- // public void onNegativeClick(View view) {
- //
- // }
- // });
- // } else if (position == 1) {
- // BuyServiceActivity.toBuyServiceActivity(ChatActivity.this, BuyServiceActivity.INTENT_FROM_INTERCEPT,
- // IConfigConstant.PAY_TAG_FROM_CHAT, IConfigConstant.PAY_WAY_ALL);
- // }
- // dialog.dismiss();
- // }
- // });
- // }
- //
- // /**
- // * 发送文字消息
- // */
- // private void sendTextMessage() {
- // OkHttpUtils.post()
- // .url(IUrlConstant.URL_SEND_TEXT_MSG)
- // .addHeader("token", PlatformInfoXml.getToken())
- // .addParams("platformInfo", PlatformInfoXml.getPlatformJsonString())
- // .addParams("uid", mUserId)
- // .addParams("writeMsgType", "1")
- // .addParams("content", mEtInput.getText().toString().trim())
- // .build()
- // .execute(new Callback<WriteMsg>() {
- // @Override
- // public WriteMsg parseNetworkResponse(Response response, int id) throws Exception {
- // String resultJson = response.body().string();
- // if (!TextUtils.isEmpty(resultJson)) {
- // return JSON.parseObject(resultJson, WriteMsg.class);
- // }
- // return null;
- // }
- //
- // @Override
- // public void onError(Call call, Exception e, int id) {
- // ToastUtil.showShortToast(ChatActivity.this, getString(R.string.send_fail));
- // mBtnSend.setEnabled(true);
- // }
- //
- // @Override
- // public void onResponse(WriteMsg response, int id) {
- // if (response != null) {
- // String isSucceed = response.getIsSucceed();
- // if (!TextUtils.isEmpty(isSucceed) && "1".equals(isSucceed)) {
- // // 重置状态
- // mEtInput.setText("");
- // loadMsgList();
- // // 发送事件,更新聊天列表
- // EventBus.getDefault().post(new MessageChangedEvent());
- // } else {
- // ToastUtil.showShortToast(ChatActivity.this, getString(R.string.send_fail));
- // }
- // } else {
- // ToastUtil.showShortToast(ChatActivity.this, getString(R.string.send_fail));
- // }
- // mBtnSend.setEnabled(true);
- // }
- // });
- // }
- //
- // /**
- // * 发送语音消息
- // */
- // private void sendVoiceMsg() {
- // // 发送语音前显示要发送的图片进度
- // final Message message = new Message();
- // if (mChatAdapter != null) {
- // mChatAdapter.isShowVoiceLoading(true);
- // mChatAdapter.isShowVoiceRetry(false);
- // message.setUid(UserInfoXml.getUID());
- // message.setMsgType("7");
- // message.setCreateDateMills(System.currentTimeMillis());
- // message.setRecevStatus("1");
- // message.setAudioTime(String.valueOf(Math.round(mRecordDuration / 1000)));
- // message.setAudioUrl(mOutputPath);
- // mChatAdapter.insertItem(mChatAdapter.getItemCount(), message);
- // // 滚动到底部
- // mLinearLayoutManager.scrollToPosition(mChatAdapter.getItemCount() - 1);
- // }
- // OkHttpUtils.post()
- // .url(IUrlConstant.URL_SEND_VOICE_MSG)
- // .addHeader("token", PlatformInfoXml.getToken())
- // .addHeader("platformInfo", PlatformInfoXml.getPlatformJsonString())
- // .addHeader("uid", mUserId)
- // .addHeader("writeMsgType", "1")
- // .addHeader("audioSecond", String.valueOf(Math.round(mRecordDuration / 1000)))
- // .addFile("file", mRecordFileName, new File(mOutputPath))
- // .build()
- // .execute(new Callback<BaseModel>() {
- // @Override
- // public BaseModel parseNetworkResponse(Response response, int id) throws Exception {
- // String resultJson = response.body().string();
- // if (!TextUtils.isEmpty(resultJson)) {
- // return JSON.parseObject(resultJson, BaseModel.class);
- // }
- // return null;
- // }
- //
- // @Override
- // public void onError(Call call, Exception e, int id) {
- // sendVoiceFailed(message);
- // }
- //
- // @Override
- // public void onResponse(BaseModel response, int id) {
- // if (response != null) {
- // String isSucceed = response.getIsSucceed();
- // if (!TextUtils.isEmpty(isSucceed) && "1".equals(isSucceed)) {
- // loadMsgList();
- // // 发送事件,更新聊天列表
- // EventBus.getDefault().post(new MessageChangedEvent());
- // } else {
- // sendVoiceFailed(message);
- // }
- // } else {
- // sendVoiceFailed(message);
- // }
- // }
- // });
- // }
- //
- // /**
- // * 发送语音失败,刷新状态
- // */
- // private void sendVoiceFailed(Message message) {
- // mChatAdapter.isShowVoiceLoading(false);
- // mChatAdapter.isShowVoiceRetry(true);
- // mChatAdapter.updateItem(mChatAdapter.getItemCount() - 1, message);
- // ToastUtil.showShortToast(ChatActivity.this, getString(R.string.send_fail));
- // }
- //
- // /**
- // * 发送图片消息
- // */
- // private void sendPhotoMsg(File file, final Message message) {
- // OkHttpUtils.post()
- // .url(IUrlConstant.URL_SEND_PHOTO_MSG)
- // .addHeader("token", PlatformInfoXml.getToken())
- // .addHeader("platformInfo", PlatformInfoXml.getPlatformJsonString())
- // .addHeader("recevUserId", mUserId)
- // .addFile("request", file.getName(), file)
- // .build()
- // .execute(new Callback<BaseModel>() {
- // @Override
- // public BaseModel parseNetworkResponse(Response response, int id) throws Exception {
- // String resultJson = response.body().string();
- // if (!TextUtils.isEmpty(resultJson)) {
- // return JSON.parseObject(resultJson, BaseModel.class);
- // }
- // return null;
- // }
- //
- // @Override
- // public void onError(Call call, Exception e, int id) {
- // sendPhotoFailed(message);
- // }
- //
- // @Override
- // public void onResponse(BaseModel response, int id) {
- // if (response != null) {
- // String isSucceed = response.getIsSucceed();
- // if (!TextUtils.isEmpty(isSucceed) && "1".equals(isSucceed)) {
- // loadMsgList();
- // // 发送事件,更新聊天列表
- // EventBus.getDefault().post(new MessageChangedEvent());
- // } else {
- // sendPhotoFailed(message);
- // }
- // } else {
- // sendPhotoFailed(message);
- // }
- // }
- // });
- // }
- //
- // /**
- // * 发送图片失败,刷新状态
- // */
- // private void sendPhotoFailed(Message message) {
- // mChatAdapter.isShowImgLoading(false);
- // mChatAdapter.isShowImgRetry(true);
- // mChatAdapter.updateItem(mChatAdapter.getItemCount() - 1, message);
- // ToastUtil.showShortToast(ChatActivity.this, getString(R.string.send_fail));
- // }
- //
- // @Override
- // protected void doRegister() {
- // super.doRegister();
- // EventBus.getDefault().register(this);
- // }
- //
- // @Override
- // protected void unregister() {
- // super.unregister();
- // EventBus.getDefault().unregister(this);
- // // 释放录音和播放器资源
- // RecordUtil.getInstance().releaseRecord();
- // if (RecordUtil.getInstance().isPlaying()) {// 如果正在播放语音,需要停止
- // RecordUtil.getInstance().stop();
- // }
- // RecordUtil.getInstance().release();
- // }
- //
- // @Subscribe
- // public void onEvent(RefreshChatEvent event) {
- // loadMsgList();
- // }
- //
- //}