PrivateActivity.java 39.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
package com.cnlive.im.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
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.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cnlive.im.R;
import com.cnlive.im.adapter.ChatRoomAdpter;
import com.cnlive.im.adapter.base.ItemClickListener;
import com.cnlive.im.mode.CNMessageModole;
import com.cnlive.im.mode.ImagMessage;
import com.cnlive.im.mode.StringMessage;
import com.cnlive.im.mode.UgcVideoMessage;
import com.cnlive.im.mode.VideoMessage;
import com.cnlive.im.mode.VoiceMessage;
import com.cnlive.im.util.AudioRecordUtil;
import com.cnlive.im.util.FileUtil;
import com.cnlive.im.util.MediaUtil;
import com.cnlive.im.util.MessageType;
import com.cnlive.im.util.TimeUtils;
import com.cnlive.im.util.ToStringUtils;
import com.cnlive.libs.util.chat.ChatUtil;
import com.cnlive.libs.util.chat.base.IChat;
import com.cnlive.libs.util.chat.model.CNBaseMessage;
import com.cnlive.libs.util.chat.model.CNImgMessage;
import com.cnlive.libs.util.chat.model.CNMessage;
import com.cnlive.libs.util.chat.model.CNUgcMessage;
import com.cnlive.libs.util.chat.model.CNUserInfo;
import com.cnlive.libs.util.chat.model.CNVideoMessage;
import com.cnlive.libs.util.chat.model.CNVoiceMessage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

import static com.cnlive.im.R.id.opposite_id_edit;

/**
 * Created by Lynn on 2017/7/24.
 */

public class PrivateActivity extends AppCompatActivity implements View.OnClickListener, ItemClickListener {

    private static final String TAG = "PrivateChatActivity";

    private final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 0x2001;

    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    public static final int IMG_FROM_PICTURE = 0x1001;
    public static final int VOICE = 0x1002;
    public static final int PICTURE_REQUEST_CODE = 0x1003;
    public static final int VOICE_REQUEST_CODE = 0x1004;

    public static final String IMAGE_MESSAGE = "image_message";
    public static final String STRING_MESSAGE = "string_message";
    public static final String VOICE_MESSAGE = "voice_message";

    private RecyclerView chatListView;
    private EditText messageContent;
    private Button sendMessageBtn;
    private ChatRoomAdpter chatListAdapter;
    private ArrayList<String> msgIds = new ArrayList<>();
    //    private CNMessage cnMessage;
    private LinearLayout linearLayoutUseID;
    private EditText user_id_edit;
    private Button userId_btn_top;
    private String oppositeID;
    private LinearLayout edit_layout;
    private Handler mHandler;
    private EditText opposite_name_edit;
    private String user_name_string;
    private String user_id_string;
    private int sendInfo = 3;
    private Button agree_btn;
    private Button reject_btn;
    private LinearLayout agree_reject_lin;
    boolean isCanSendMeaasge = false;
    private Button vistor_btn;

    private ImageView keybordBtn;
    private Button sendVoice;
    private AudioRecordUtil mAudioRecordUtil;
    private String mFilePath;
    private PopupWindowFactory mPop;
    private RelativeLayout privateLayout;
    private LinearLayout sendMsgLayout;
    private LinearLayout cancelSendLayout;
    private TextView mTextView;
    private ImageView mImageView;
    private ImageView ima_send;

    private boolean isVoiceBtnVisible = false;
    private int duration;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_private_chat);
        context = this;
        initView();
        mAudioRecordUtil = new AudioRecordUtil();
        mAudioRecordUtil.setOnAudioStatusUpdateListener(onAudioStatusUpdateListener);
        mHandler = new Handler();
        ChatUtil.setOnConnectStatusListener(connectStatusListener);
        ChatUtil.setOnReceivePrivateMessageListener(receiveMessageListener);
        ChatUtil.setUploadProgressListener(uploadProgressListener);
        requestPermission();
    }

    private void initView() {

        final View view = View.inflate(this, R.layout.layout_microphone, null);
        mPop = new PopupWindowFactory(this, view);
        sendMsgLayout = (LinearLayout) view.findViewById(R.id.send_layout);
        cancelSendLayout = (LinearLayout) view.findViewById(R.id.cancel_send_layout);
        mTextView = (TextView) view.findViewById(R.id.tv_recording_time);
        mImageView = (ImageView) view.findViewById(R.id.iv_recording_icon);

        opposite_name_edit = (EditText) findViewById(R.id.opposite_name_edit);
        chatListView = (RecyclerView) findViewById(R.id.private_list_view);

        privateLayout = (RelativeLayout) findViewById(R.id.activity_private_chat);

        messageContent = (EditText) findViewById(R.id.message_content);
        messageContent.addTextChangedListener(textWatcher);
        sendMessageBtn = (Button) findViewById(R.id.send_message);
        sendMessageBtn.setOnClickListener(this);
        linearLayoutUseID = (LinearLayout) findViewById(R.id.opposite_liner_useID);
        userId_btn_top = (Button) findViewById(R.id.userId_btn_top);
        userId_btn_top.setOnClickListener(this);
        edit_layout = (LinearLayout) findViewById(R.id.edit_layout);
        user_id_edit = (EditText) findViewById(opposite_id_edit);
        Intent intent = getIntent();
        user_name_string = intent.getStringExtra("user_name_string");
        user_id_string = intent.getStringExtra("user_id_string");
        agree_btn = (Button) findViewById(R.id.agree_btn);
        reject_btn = (Button) findViewById(R.id.reject_btn);
        agree_btn.setOnClickListener(this);
        reject_btn.setOnClickListener(this);
        agree_reject_lin = (LinearLayout) findViewById(R.id.agree_reject_lin);
        vistor_btn = (Button) findViewById(R.id.vistor_Btn);
        vistor_btn.setOnClickListener(this);

        keybordBtn = (ImageView) findViewById(R.id.keybord);
        keybordBtn.setOnClickListener(this);

        ima_send = (ImageView) findViewById(R.id.ima_send);
        ima_send.setOnClickListener(this);

        sendVoice = (Button) findViewById(R.id.send_voice);

        chatListAdapter = new ChatRoomAdpter(this, true);
        chatListAdapter.setonVoiceItemClickListener(this);
        chatListView.setLayoutManager(new LinearLayoutManager(PrivateActivity.this));
        chatListView.setAdapter(chatListAdapter);

        findViewById(R.id.videoBtn).setOnClickListener(this);
        findViewById(R.id.ugcVideoBtn).setOnClickListener(this);

        StartListener();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.send_message:
                sendMessage(STRING_MESSAGE);

                break;

            case R.id.userId_btn_top:
                //发送私聊消息,需要传入目标ID与发送的消息内容
                if (user_id_edit.getText().toString().isEmpty()) {
                    Toast.makeText(this, "对方ID不能为空", Toast.LENGTH_SHORT).show();
                } else if (opposite_name_edit.getText().toString().isEmpty()) {
                    Toast.makeText(this, "对方name不能为空", Toast.LENGTH_SHORT).show();
                } else {

                    oppositeID = user_id_edit.getText().toString();
                    linearLayoutUseID.setVisibility(View.INVISIBLE);
                    edit_layout.setVisibility(View.VISIBLE);
                    chatListView.setVisibility(View.VISIBLE);
                    CNUserInfo cnName = new CNUserInfo(user_id_string, user_name_string, "");
                    ChatUtil.login(cnName, connectListener);

                }

                break;

            case R.id.agree_btn:
                String objToJsonString = ToStringUtils.objToJsonString(new CNMessageModole("同意", "3"));
                ChatUtil.sendMessage(IChat.PRIVATE, oppositeID, objToJsonString, sendMessageListener);
                agree_reject_lin.setVisibility(View.GONE);
                break;

            case R.id.reject_btn:
                String objToJsonStringDis = ToStringUtils.objToJsonString(new CNMessageModole("拒绝", "3"));//私聊

                ChatUtil.sendMessage(IChat.PRIVATE, oppositeID, objToJsonStringDis, sendMessageListener);
                agree_reject_lin.setVisibility(View.GONE);
                break;
            case R.id.vistor_Btn:
                String objToJsonStringInvt = ToStringUtils.objToJsonString(new CNMessageModole("你好我们可以进行私聊吗", "3"));//私聊
                ChatUtil.sendMessage(IChat.PRIVATE, oppositeID, objToJsonStringInvt, sendMessageListener);

                break;

            case R.id.keybord:
                if (!isVoiceBtnVisible) {
                    messageContent.setVisibility(View.GONE);
                    sendVoice.setVisibility(View.VISIBLE);
                    keybordBtn.setImageResource(R.drawable.keybord);
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(messageContent.getWindowToken(), 0);
                    isVoiceBtnVisible = true;
                } else {
                    sendVoice.setVisibility(View.GONE);
                    messageContent.setVisibility(View.VISIBLE);
                    keybordBtn.setImageResource(R.drawable.voice);
                    isVoiceBtnVisible = false;
                }
                break;
            case R.id.ima_send:
                sendMessage(IMAGE_MESSAGE);
                break;
            case R.id.videoBtn:
                openSystemRecorder();
                break;
            case R.id.ugcVideoBtn:
                openSystemRecorder();
                break;
        }
    }

    private void openSystemRecorder() {
        // 创建拍照Intent并将控制权返回给调用的程序
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);

        // 保存录像到指定的路径
        File file = new File("/sdcard/video.mp4");
        Uri uri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        // 启动图像捕获Intent
        startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
    }


    private void sendMessage(String type) {
        if (sendInfo == 2) {
            Toast.makeText(this, "等待对方接受邀请", Toast.LENGTH_SHORT).show();

        } else if (sendInfo == 4) {
            Toast.makeText(this, "对方已经拒绝不能发送", Toast.LENGTH_SHORT).show();

        } else if (sendInfo == 3) {
            Toast.makeText(this, "还没有邀请对方呦~", Toast.LENGTH_SHORT).show();
        } else if (sendInfo == 5) {
            Toast.makeText(this, "你已经拒绝对方不能发送消息", Toast.LENGTH_SHORT).show();
        } else {
            if (type.equals(STRING_MESSAGE)) {
                if (messageContent.getText().toString().isEmpty()) {
                    Toast.makeText(this, "不能发送空消息呦~", Toast.LENGTH_SHORT).show();
                } else {
                    String objToJsonString = ToStringUtils.objToJsonString(new CNMessageModole(messageContent.getText().toString(), "4"));//私聊消息
                    ChatUtil.sendMessage(IChat.PRIVATE, oppositeID, objToJsonString, sendMessageListener);
                    messageContent.setText("");
                }
            } else if (type.equals(IMAGE_MESSAGE)) {
                fromPicture();
            } else if (type.equals(VOICE_MESSAGE)) {
                mPop.showAtLocation(privateLayout, Gravity.CENTER, 0, 0);

                sendVoice.setText("松开发送");
                mAudioRecordUtil.startRecord();
            }
        }
    }

    public void fromPicture() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(PrivateActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICTURE_REQUEST_CODE);
                return;
            } else {
                toIntentPicture();
            }
        } else {
            toIntentPicture();
        }
    }


    private void toIntentPicture() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_PICK);
        startActivityForResult(Intent.createChooser(intent, "Complete action using"), IMG_FROM_PICTURE);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case IMG_FROM_PICTURE:
//                    String localImagePath = "/sdcard/test.png";
//                    Uri selectedImage = Uri.parse("file://" + localImagePath);
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};

                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();

                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    final String picturePath = cursor.getString(columnIndex);

                    Uri uri = Uri.parse("file://" + picturePath);
                    ChatUtil.sendImaMessage(IChat.PRIVATE, oppositeID, uri, uri, sendMessageListener);
                    break;
                case CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE:
                    String videoPath = data.getData().getPath();
                    Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Images.Thumbnails.FULL_SCREEN_KIND);
                    String imgPath = FileUtil.createFile(bitmap, System.currentTimeMillis() + "");
                    ChatUtil.sendVideoMessage(IChat.PRIVATE, oppositeID, videoPath, imgPath, MediaUtil.getInstance().getDuration(videoPath), sendMessageListener);
                    break;

                default:
                    break;
            }
        }
    }

    //连接监听
    private IChat.OnConnectListener connectListener = new IChat.OnConnectListener() {


        @Override
        public void onTokenIncorrect(String s) {
            Log.e(TAG, "ConnectListener TokenIncorrect");
            Toast.makeText(PrivateActivity.this, "TokenIncorrect", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onSuccess(String s) {
            Log.e(TAG, "ConnectListener 连接监听" + s);
            Toast.makeText(PrivateActivity.this, s, Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onError(int i, String s) {
            Log.e(TAG, "ConnectListener errorCode : " + i + " : errorMessage : " + s);
            Toast.makeText(PrivateActivity.this, s, Toast.LENGTH_SHORT).show();

        }
    };


    /**
     * 发送消息监听
     */
    private IChat.OnSendMessageListener sendMessageListener = new IChat.OnSendMessageListener() {
        @Override
        public void onAttached(CNBaseMessage o) {
            showMessage(o, false);
        }

        @Override
        public void onSuccess(final CNBaseMessage o) {
            updateItem(o, -1);
        }

        @Override
        public void onError(CNBaseMessage o, int i, String s) {
            updateItem(o, -1);
        }
    };

    //连接状态监听
    private IChat.OnConnectStatusListener connectStatusListener = new IChat.OnConnectStatusListener() {
        @Override
        public void onConnectStatus(int i, String s) {
            Log.i(TAG, "连接状态监听" + i + "   " + s);
        }
    };


    //接收消息监听
    private IChat.OnReceiveMessageListener receiveMessageListener = new IChat.OnReceiveMessageListener() {
        @Override
        public void processMessage(final CNBaseMessage o) {
            if (!o.getTargetId().equals(oppositeID)) return;
            showMessage(o, true);
        }
    };

    private IChat.OnUploadProgressListener uploadProgressListener = new IChat.OnUploadProgressListener() {
        @Override
        public void onMessagesUpdate(CNBaseMessage message, int elemIdx, int taskId, int progress) {
            if (!message.getTargetId().equals(oppositeID)) return;
            updateItem(message, progress);
        }
    };

    /**
     * 更新消息
     */
    public void updateItem(CNBaseMessage o, int progress) {
        int updateIndex = msgIds.indexOf(o.getMessageId());
        if (updateIndex < 0 || chatListAdapter.getItemCount() <= 0 || updateIndex > chatListAdapter.getItemCount() - 1)
            return;
        if (o.getMsgType() == IChat.CN_MSG_TYPE_TEXT) {
            CNMessage o1 = (CNMessage) o;
            chatListAdapter.updateItem(new StringMessage(MessageType.stringMessage, o1, o1.isSelf()), updateIndex);
        } else if (o.getMsgType() == IChat.CN_MSG_TYPE_IMAGE) {
            CNImgMessage o1 = (CNImgMessage) o;
            chatListAdapter.updateItem(new ImagMessage(MessageType.imaMessage, o1, o1.isSelf(), progress < 0 ? 0 : progress), updateIndex);
        } else if (o.getMsgType() == IChat.CN_MSG_TYPE_VOICE) {
            CNVoiceMessage o1 = (CNVoiceMessage) o;
            VoiceMessage voiceMessage = new VoiceMessage(MessageType.voiceMessage, o1, o1.isSelf(), progress < 0 ? 0 : progress);
            chatListAdapter.updateItem(voiceMessage, updateIndex);
        } else if (o.getMsgType() == IChat.CN_MSG_TYPE_VIDEO) {
            CNVideoMessage ol = (CNVideoMessage) o;
            VideoMessage videoMessage = new VideoMessage(MessageType.videoMessage, ol, ol.isSelf(), progress < 0 ? 0 : progress);
            chatListAdapter.updateItem(videoMessage, updateIndex);
        } else if (o.getMsgType() == IChat.CN_MSG_TYPE_UGC) {
            CNUgcMessage ol = (CNUgcMessage) o;
            UgcVideoMessage ugcVideoMessage = new UgcVideoMessage(MessageType.ugcVideoMessage, ol, ol.isSelf(), progress < 0 ? 0 : progress);
            chatListAdapter.updateItem(ugcVideoMessage, updateIndex);
        }
    }

    /**
     * 展示消息
     *
     * @param o
     */
    private void showMessage(CNBaseMessage o, boolean isReceivedMsg) {
        if (o.getMsgType() == IChat.CN_MSG_TYPE_TEXT) {
            if (isReceivedMsg) {
                CNMessage o1 = (CNMessage) o;
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(o1.getContent().toString());
                    String type = (String) jsonObject.get("type");
                    if ("3".equals(type) && "你好我们可以进行私聊吗".equals(jsonObject.get("message"))) {
                        vistor_btn.setVisibility(View.GONE);
                        agree_reject_lin.setVisibility(View.VISIBLE);
                    } else if ("3".equals(type) && "同意".equals(jsonObject.get("message"))) {
                        sendInfo = 1;
                    } else if ("3".equals(type) && "拒绝".equals(jsonObject.get("message"))) {
                        sendInfo = 4;
                    } else if ("4".equals(type)) {
                        Log.v(TAG, o1.getContent().toString());
                        msgIds.add(o.getMessageId());
                        chatListAdapter.addItem(new StringMessage(MessageType.stringMessage, o1, false));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                CNMessage o1 = (CNMessage) o;
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(o1.getContent().toString());
                    String type = (String) jsonObject.get("type");
                    String message = (String) jsonObject.get("message");
                    Toast.makeText(PrivateActivity.this, "发送消息成功", Toast.LENGTH_SHORT).show();
                    if ("3".equals(type) && message.equals("你好我们可以进行私聊吗")) {
                        sendInfo = 2;
                        Toast.makeText(PrivateActivity.this, "申请已发送等待对方验证", Toast.LENGTH_SHORT).show();
                    } else if ("3".equals(type) && message.equals("拒绝")) {
                        sendInfo = 5;
                    } else if ("3".equals(type) && message.equals("同意")) {
                        sendInfo = 1;
                    } else if ("4".equals(type)) {
                        msgIds.add(o.getMessageId());
                        chatListAdapter.addItem(new StringMessage(MessageType.stringMessage, o1, true));
                    }
                } catch (JSONException e) {
                }
            }
        } else if (o.getMsgType() == IChat.CN_MSG_TYPE_IMAGE) {
            msgIds.add(o.getMessageId());
            CNImgMessage o1 = (CNImgMessage) o;
            chatListAdapter.addItem(new ImagMessage(MessageType.imaMessage, o1, o1.isSelf()));
        } else if (o.getMsgType() == IChat.CN_MSG_TYPE_VOICE) {
            msgIds.add(o.getMessageId());
            CNVoiceMessage o1 = (CNVoiceMessage) o;
            VoiceMessage voiceMessage = new VoiceMessage(MessageType.voiceMessage, o1, o1.isSelf());
            chatListAdapter.addItem(voiceMessage);
        } else if (o.getMsgType() == IChat.CN_MSG_TYPE_VIDEO) {
            msgIds.add(o.getMessageId());
            CNVideoMessage ol = (CNVideoMessage) o;
            VideoMessage videoMessage = new VideoMessage(MessageType.videoMessage, ol, ol.isSelf());
            chatListAdapter.addItem(videoMessage);
        } else if (o.getMsgType() == IChat.CN_MSG_TYPE_UGC) {
            msgIds.add(o.getMessageId());
            CNUgcMessage ol = (CNUgcMessage) o;
            UgcVideoMessage ugcVideoMessage = new UgcVideoMessage(MessageType.ugcVideoMessage, ol, ol.isSelf());
            chatListAdapter.addItem(ugcVideoMessage);
        }
        if (chatListAdapter.getItemCount() > 0)
            chatListView.smoothScrollToPosition(chatListAdapter.getItemCount() - 1);
    }

    /**
     * 开启扫描之前判断权限是否打开
     */
    private void requestPermission() {
        //判断是否开启摄像头权限
        if ((ContextCompat.checkSelfPermission(context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) &&
                (ContextCompat.checkSelfPermission(context,
                        Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)
                && (ContextCompat.checkSelfPermission(context,
                Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)) {
            StartListener();

            //判断是否开启语音权限
        } else {
            //请求获取摄像头权限
            ActivityCompat.requestPermissions((Activity) context,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA}, VOICE_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == VOICE_REQUEST_CODE) {
            if ((grantResults[0] == PackageManager.PERMISSION_GRANTED) && (grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                StartListener();
            } else {
                Toast.makeText(context, "已拒绝权限!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    float downX;
    float downY;

    public void StartListener() {

        //Button的touch监听
        sendVoice.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (lacksPermissions(PERMISSIONS)) {
                    if (lacksPermission(PERMISSIONS[0])) {
                        Toast.makeText(PrivateActivity.this, "没有麦克风权限,请前往“设置 - 应用 - 权限”中开启权限", Toast.LENGTH_SHORT).show();

                    } else if (lacksPermission(PERMISSIONS[1])) {
                        Toast.makeText(PrivateActivity.this, "没有文件读写权限,请前往“设置 - 应用 - 权限”中开启权限", Toast.LENGTH_SHORT).show();

                    }
                } else {

                    switch (event.getAction()) {

                        case MotionEvent.ACTION_DOWN:
                            sendMessage(VOICE_MESSAGE);
//                            mPop.showAtLocation(privateLayout, Gravity.CENTER, 0, 0);
//
//                            sendVoice.setText("松开发送");
//                            mAudioRecordUtil.startRecord();
                            downX = event.getX();
                            downY = event.getY();

                            break;

                        case MotionEvent.ACTION_UP:

                            if (cancelSendLayout.getVisibility() == View.VISIBLE) {
                                cancelSendLayout.setVisibility(View.GONE);
                                sendMsgLayout.setVisibility(View.VISIBLE);
                            }
                            float moveX = Math.abs(event.getX() - downX);
                            float moveY = Math.abs(event.getY() - downY);
                            if (moveY > 100) {
//                                Toast.makeText(PrivateActivity.this, "cancel", Toast.LENGTH_SHORT).show();
                                mAudioRecordUtil.cancelRecord();
                            } else {
                                mAudioRecordUtil.stopRecord();        //结束录音(保存录音文件)
                            }
                            mPop.dismiss();
                            mTextView.setText("00:00");
                            sendVoice.setText("按住说话");
                            break;
                        case MotionEvent.ACTION_MOVE:
                            float moveXm = Math.abs(event.getX() - downX);
                            float moveYm = Math.abs(event.getY() - downY);
                            if (moveYm > 100) {
//                                Toast.makeText(PrivateActivity.this, "cancel", Toast.LENGTH_SHORT).show();
                                if (sendMsgLayout.getVisibility() == View.VISIBLE) {
                                    sendMsgLayout.setVisibility(View.GONE);
                                    cancelSendLayout.setVisibility(View.VISIBLE);
                                }
                            } else {
                                if (cancelSendLayout.getVisibility() == View.VISIBLE) {
                                    cancelSendLayout.setVisibility(View.GONE);
                                    sendMsgLayout.setVisibility(View.VISIBLE);
                                }
                            }
                            break;
                    }
                }
                return true;
            }
        });

    }

    // 判断权限集合
    public boolean lacksPermissions(String... permissions) {
        for (String permission : permissions) {
            if (lacksPermission(permission)) {
                return true;
            }
        }
        return false;
    }

    // 判断是否缺少权限
    private boolean lacksPermission(String permission) {
        return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED;
    }

    private AudioRecordUtil.OnAudioStatusUpdateListener onAudioStatusUpdateListener = new AudioRecordUtil.OnAudioStatusUpdateListener() {
        @Override
        public void onUpdate(double db, long time) {
            mImageView.getDrawable().setLevel((int) (3000 + 6000 * db / 100));
            mTextView.setText(TimeUtils.long2String(time));
        }

        @Override
        public void onStop(String filePath) {
            duration = (int) mAudioRecordUtil.getDuration();
            mFilePath = filePath;
            ChatUtil.sendVoiceMessage(IChat.PRIVATE, oppositeID, Uri.parse(mFilePath), duration, sendMessageListener);
        }
    };

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!TextUtils.isEmpty(editable)) {
                ima_send.setVisibility(View.GONE);
                sendMessageBtn.setVisibility(View.VISIBLE);
            } else {
                sendMessageBtn.setVisibility(View.GONE);
                ima_send.setVisibility(View.VISIBLE);
            }
        }
    };

    /**
     * 播放语音文件
     *
     * @param voicePath
     * @param animationDrawable
     */
    private void startVoice(String voicePath, final AnimationDrawable animationDrawable) {
        try {
            FileInputStream fis = new FileInputStream(voicePath);
            MediaUtil.getInstance().play(fis);
            animationDrawable.start();
            MediaUtil.getInstance().setEventListener(new MediaUtil.EventListener() {
                @Override
                public void onStop() {
                    animationDrawable.stop();
                    animationDrawable.selectDrawable(0);
                }
            });
        } catch (Exception e) {
        }
    }

    @Override
    public void onItemClick(final VoiceMessage voiceMessage, final AnimationDrawable animationDrawable) {
        if (voiceMessage == null) {
            Toast.makeText(this, "数据异常", Toast.LENGTH_LONG).show();
            return;
        }
        if (voiceMessage.getCnVoiceMessage().isSelf()) {
            startVoice(voiceMessage.getCnVoiceMessage().getVoiceUri().getPath(), animationDrawable);
        } else {
            //设置本地已读
            voiceMessage.getCnVoiceMessage().setRead(true);
            String voiceUuid = voiceMessage.getCnVoiceMessage().getUuid();
            final String voicePath = FileUtil.getCacheFilePath(voiceUuid);
            if (FileUtil.isCacheFileExist(voiceUuid)) {
                File file = new File(voicePath);
                if (file.length() < voiceMessage.getCnVoiceMessage().getDataSize()) {
                    Toast.makeText(context, "请稍等,正在下载...", Toast.LENGTH_SHORT).show();
                    return;
                }
                startVoice(voicePath, animationDrawable);
            } else {
                if (voiceMessage.isDownloading()) {
                    Toast.makeText(context, "请稍等,正在下载...", Toast.LENGTH_SHORT).show();
                } else {
                    voiceMessage.setDownloading(true);
                    voiceMessage.getCnVoiceMessage().getVoice(voicePath, new IChat.OnDownloadListener() {
                        @Override
                        public void onSuccess() {
                            voiceMessage.setDownloading(false);
                            startVoice(voicePath, animationDrawable);
                        }

                        @Override
                        public void onError(int i, String s) {
                            voiceMessage.setDownloading(false);
                        }
                    });
                }
            }
        }
    }

    @Override
    public void onVideoClick(final VideoMessage videoMessage) {
        if (videoMessage.getCnVideoMessage().isSelf()) {
            Intent intent = new Intent(PrivateActivity.this, VideoActivity.class);
            intent.putExtra("videoPath", videoMessage.getCnVideoMessage().getVideoPath());
            startActivity(intent);
        } else {
            String videoUuid = videoMessage.getCnVideoMessage().getVideo().getUuid();
            final String videoPath = FileUtil.getCacheFilePath(videoUuid);
            if (FileUtil.isCacheFileExist(videoUuid)) {
                File file = new File(videoPath);
                if (file.length() < videoMessage.getCnVideoMessage().getVideo().getSize()) {
                    Toast.makeText(context, "请稍等,正在下载...", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(PrivateActivity.this, VideoActivity.class);
                intent.putExtra("videoPath", videoPath);
                startActivity(intent);
            } else {
                if (videoMessage.isDownloading()) {
                    Toast.makeText(context, "请稍等,正在下载...", Toast.LENGTH_SHORT).show();
                } else {
                    videoMessage.setDownloading(true);
                    videoMessage.getCnVideoMessage().getVideo().getVideo(videoPath, new IChat.OnDownloadListener() {
                        @Override
                        public void onSuccess() {
                            videoMessage.setDownloading(false);
                            Intent intent = new Intent(PrivateActivity.this, VideoActivity.class);
                            intent.putExtra("videoPath", videoPath);
                            startActivity(intent);
                        }

                        @Override
                        public void onError(int i, String s) {
                            videoMessage.setDownloading(false);
                        }
                    });
                }
            }
        }

    }

    @Override
    public void onUgcVideoClick(final UgcVideoMessage ugcVideoMessage) {
        if (ugcVideoMessage.getCnUgcMessage().isSelf()) {
            Intent intent = new Intent(PrivateActivity.this, VideoActivity.class);
            intent.putExtra("videoPath", ugcVideoMessage.getCnUgcMessage().getVideoPath());
            startActivity(intent);
        } else {
            String videoUuid = ugcVideoMessage.getCnUgcMessage().getFileId() + "_video";
            final String videoPath = FileUtil.getCacheFilePath(videoUuid);
            if (FileUtil.isCacheFileExist(videoUuid)) {
                File file = new File(videoPath);
                if (file.length() < ugcVideoMessage.getCnUgcMessage().getVideo().getSize()) {
                    Toast.makeText(context, "请稍等,正在下载...", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(PrivateActivity.this, VideoActivity.class);
                intent.putExtra("videoPath", videoPath);
                startActivity(intent);
            } else {
                if (ugcVideoMessage.isDownloading()) {
                    Toast.makeText(context, "请稍等,正在下载...", Toast.LENGTH_SHORT).show();
                } else {
                    ugcVideoMessage.setDownloading(true);
                    ugcVideoMessage.getCnUgcMessage().getVideo().getVideo(videoPath, new IChat.OnDownloadListener() {
                        @Override
                        public void onSuccess() {
                            ugcVideoMessage.setDownloading(false);
                            Intent intent = new Intent(PrivateActivity.this, VideoActivity.class);
                            intent.putExtra("videoPath", videoPath);
                            startActivity(intent);
                        }

                        @Override
                        public void onError(int i, String s) {
                            ugcVideoMessage.setDownloading(false);
                        }
                    });
                }
            }
        }
    }

    @Override
    public void onImageClick(final ImagMessage imagMessage) {
        if (imagMessage.getCnImgMessage().isSelf()) {
            Intent intent = new Intent(PrivateActivity.this, ImageViewActivity.class);
            intent.putExtra("path", imagMessage.getCnImgMessage().getImagePath());
            startActivity(intent);
        } else {
            String remoteUuid = imagMessage.getCnImgMessage().getRemoteUuid();
            final String imagePath = FileUtil.getCacheFilePath(remoteUuid);
            if (FileUtil.isCacheFileExist(remoteUuid)) {
                File file = new File(imagePath);
                if (file.length() < imagMessage.getCnImgMessage().getRemoteSize()) {
                    Toast.makeText(context, "请稍等,正在下载...", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(PrivateActivity.this, ImageViewActivity.class);
                intent.putExtra("path", imagePath);
                startActivity(intent);
            } else {
                if (imagMessage.isDownloading()) {
                    Toast.makeText(context, "请稍等,正在下载...", Toast.LENGTH_SHORT).show();
                } else {
                    imagMessage.setDownloading(true);
                    imagMessage.getCnImgMessage().getRemoteImage(imagePath, new IChat.OnDownloadListener() {
                        @Override
                        public void onSuccess() {
                            imagMessage.setDownloading(false);
                            Intent intent = new Intent(PrivateActivity.this, ImageViewActivity.class);
                            intent.putExtra("path", imagePath);
                            startActivity(intent);
                        }

                        @Override
                        public void onError(int i, String s) {
                            imagMessage.setDownloading(false);
                            Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MediaUtil.getInstance().stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ChatUtil.removeUploadProgressListener(uploadProgressListener);
        ChatUtil.removeReceiveMessageListener(receiveMessageListener);
        ChatUtil.removeConnectListener(connectListener);
        ChatUtil.removeConnectStatusListener(connectStatusListener);
    }
}