ChatRoomActivity.java
22.7 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
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.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
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.VoiceItemClickListener;
import com.cnlive.im.mode.ImagMessage;
import com.cnlive.im.mode.StringMessage;
import com.cnlive.im.mode.VoiceMessage;
import com.cnlive.im.util.AudioRecordUtil;
import com.cnlive.im.util.FileUtil;
import com.cnlive.im.util.MessageType;
import com.cnlive.im.util.PlayerUtil;
import com.cnlive.im.util.TimeUtils;
import com.cnlive.im.util.UploadImageUtils;
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.CNUserInfo;
import com.cnlive.libs.util.chat.model.CNVoiceMessage;
import java.util.ArrayList;
/**
* @author 陈硕
* @time 2017/3/7 14:36
* @desc ${TODD}
*/
public class ChatRoomActivity extends AppCompatActivity implements View.OnClickListener, VoiceItemClickListener {
private static final String TAG = "ChatRoomActivity";
private ArrayList<Object> groupChatOneListMy;
private String roomIdOne = "ChatRoom05";
private EditText editText;
private Button send_messageOneBtn;
private RecyclerView listViewOne;
private ChatRoomAdpter chatListAdapterOne;
private Button foundChatBtn;
private Handler mHandler;
private RelativeLayout re_chat;
// private LinearLayout lin_user;
// private EditText user_id, user_name;
private Button exit_chat1;
public static String user_name_string;
private boolean isUserLogin = false;
private ImageView ima_send;
private Button sendVoice;
private Context context;
private AudioRecordUtil mAudioRecordUtil;
private PopupWindowFactory mPop;
private ImageView mImageView;
private TextView mTextView;
private ImageView keybordBtn;
private LinearLayout sendMsgLayout;
private LinearLayout cancelSendLayout;
private boolean isVoiceBtnVisible = false;
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;
private long l;
int duration;
private String mFilePath;
private PlayerUtil playerUtil;
// 所需的全部权限
static final String[] PERMISSIONS = new String[]{
Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//取消状态栏
setContentView(R.layout.activity_groupchat);
context = this;
initUI();
mAudioRecordUtil = new AudioRecordUtil();
mAudioRecordUtil.setOnAudioStatusUpdateListener(onAudioStatusUpdateListener);
//设置监听
mHandler = new Handler();
ChatUtil.setOnConnectStatusListener(connectStatusListener);
ChatUtil.setOnChatRoomActionListener(chatRoomActionListener);
ChatUtil.setOnReceiveMessageListener(receiveMessageListener);
ChatUtil.setKickedOfflineListener(onKickedOfflineListener);
Intent intent = getIntent();
user_name_string = intent.getStringExtra("user_name_string");
String user_id_string = intent.getStringExtra("user_id_string");
if (user_name_string != null)
ChatUtil.login(new CNUserInfo(user_id_string, user_name_string, ""), connectListener);
else ChatUtil.logOut(connectListener);
requestPermission();
playerUtil = new PlayerUtil(this);
}
private void initUI() {
final View view = View.inflate(this, R.layout.layout_microphone, null);
mPop = new PopupWindowFactory(this, view);
mImageView = (ImageView) view.findViewById(R.id.iv_recording_icon);
mTextView = (TextView) view.findViewById(R.id.tv_recording_time);
sendMsgLayout = (LinearLayout) view.findViewById(R.id.send_layout);
cancelSendLayout = (LinearLayout) view.findViewById(R.id.cancel_send_layout);
ima_send = (ImageView) findViewById(R.id.ima_send);
exit_chat1 = (Button) findViewById(R.id.exit_chat1);
// user_id = (EditText) findViewById(R.id.user_ID);
// user_name = (EditText) findViewById(R.id.user_name);
// lin_user = (LinearLayout) findViewById(R.id.lin_user);
re_chat = (RelativeLayout) findViewById(R.id.re_chat);
foundChatBtn = (Button) findViewById(R.id.creatChat);
listViewOne = (RecyclerView) findViewById(R.id.chat_list_viewOne);
editText = (EditText) findViewById(R.id.message_content);
editText.addTextChangedListener(textWatcher);
send_messageOneBtn = (Button) findViewById(R.id.send_messageOne);
ima_send.setOnClickListener(this);
exit_chat1.setOnClickListener(this);
foundChatBtn.setOnClickListener(this);
send_messageOneBtn.setOnClickListener(this);
groupChatOneListMy = new ArrayList<>();
chatListAdapterOne = new ChatRoomAdpter(ChatRoomActivity.this, false);
chatListAdapterOne.setonVoiceItemClickListener(this);
listViewOne.setLayoutManager(new LinearLayoutManager(ChatRoomActivity.this));
listViewOne.setAdapter(chatListAdapterOne);
sendVoice = (Button) findViewById(R.id.send_voice);
re_chat = (RelativeLayout) findViewById(R.id.activity_chat_room);
keybordBtn = (ImageView) findViewById(R.id.keybord);
keybordBtn.setOnClickListener(this);
StartListener();
}
/**
* 发送消息监听
*/
private IChat.OnSendMessageListener sendMessageListener = new IChat.OnSendMessageListener() {
@Override
public void onAttached(CNBaseMessage o) {
}
@Override
public void onSuccess(final CNBaseMessage o) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (o instanceof CNMessage) {
CNMessage o1 = (CNMessage) o;
chatListAdapterOne.addItem(new StringMessage(MessageType.stringMessage, o1, true));
} else if (o instanceof CNImgMessage) {
CNImgMessage o1 = (CNImgMessage) o;
chatListAdapterOne.addItem(new ImagMessage(MessageType.imaMessage, o1, true));
} else if (o instanceof CNVoiceMessage) {
CNVoiceMessage o1 = (CNVoiceMessage) o;
VoiceMessage voiceMessage = new VoiceMessage(MessageType.voiceMessage, o1, true);
chatListAdapterOne.addItem(voiceMessage);
//发送成功后删除保存在本地的录制文件
mAudioRecordUtil.deleteRecordFile(mFilePath);
}
listViewOne.smoothScrollToPosition(chatListAdapterOne.getItemCount() - 1);
}
});
}
@Override
public void onError(CNBaseMessage o, int i, String s) {
if (o instanceof CNImgMessage) {
}
}
};
//连接状态监听
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) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (o instanceof CNMessage) {
CNMessage o1 = (CNMessage) o;
chatListAdapterOne.addItem(new StringMessage(MessageType.stringMessage, o1, false));
} else if (o instanceof CNImgMessage) {
CNImgMessage o1 = (CNImgMessage) o;
chatListAdapterOne.addItem(new ImagMessage(MessageType.imaMessage, o1, false));
} else if (o instanceof CNVoiceMessage) {
CNVoiceMessage o1 = (CNVoiceMessage) o;
VoiceMessage voiceMessage = new VoiceMessage(MessageType.voiceMessage, o1, false);
chatListAdapterOne.addItem(voiceMessage);
}
listViewOne.smoothScrollToPosition(chatListAdapterOne.getItemCount() - 1);
}
});
}
};
//聊天室操作
private IChat.OnChatRoomActionListener chatRoomActionListener = new IChat.OnChatRoomActionListener() {
@Override
public void onJoining(String s) {
Log.i(TAG, "chatRoomActionListener" + " onJoining" + s);
}
@Override
public void onJoined(String s) {
Log.i(TAG, "chatRoomActionListener " + "onJoined" + s);
}
@Override
public void onQuited(String s) {
Log.i(TAG, "chatRoomActionListener " + "onQuited" + s);
}
@Override
public void onError(String s, int i, String s1) {
Log.i(TAG, "chatRoomActionListener " + "onError" + s);
}
};
//被踢下线状态
private IChat.OnKickedOfflineListener onKickedOfflineListener = new IChat.OnKickedOfflineListener() {
@Override
public void disconnected(int what, final String extra) {
Log.e(TAG, what + " : " + extra);
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(ChatRoomActivity.this, extra, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void conByDevId(final int what, final String extra) {
Log.e(TAG, what + " : " + extra);
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(ChatRoomActivity.this, extra, Toast.LENGTH_SHORT).show();
}
});
}
};
// 加入聊天室监听
private IChat.OnOperationListener onOperationListener = new IChat.OnOperationListener() {
@Override
public void onSuccess(int what, final String extra) {
Log.v(TAG, +what + extra);
}
@Override
public void onError(int what, String extra) {
Log.v(TAG, "加入聊天室" + what + extra);
}
};
@Override
public void onClick(View view) {
switch (view.getId()) {
//向聊天室1发送消息
case R.id.send_messageOne:
//发送聊天室消息
if (editText.getText().toString().isEmpty()) {
Toast.makeText(this, "不能发送空消息呦~", Toast.LENGTH_SHORT).show();
} else {
ChatUtil.sendMessage(IChat.CHATROOM, roomIdOne, editText.getText().toString(), sendMessageListener);
editText.setText("");
}
break;
case R.id.creatChat:
ChatUtil.joinChatRoom(roomIdOne, -1, onOperationListener);
break;
case R.id.exit_chat1:
ChatUtil.quitChatRoom(roomIdOne, onOperationListener);
break;
case R.id.ima_send:
fromPicture();
break;
case R.id.keybord:
if (!isVoiceBtnVisible) {
editText.setVisibility(View.GONE);
sendVoice.setVisibility(View.VISIBLE);
keybordBtn.setImageResource(R.drawable.keybord);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
isVoiceBtnVisible = true;
} else {
sendVoice.setVisibility(View.GONE);
editText.setVisibility(View.VISIBLE);
keybordBtn.setImageResource(R.drawable.voice);
isVoiceBtnVisible = false;
}
break;
}
}
public void fromPicture() {
if (Build.VERSION.SDK_INT >= 23) {
int checkCallPhonePermission = ContextCompat.checkSelfPermission(ChatRoomActivity.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:
Uri selectedImage = data.getData();
String picturePath = UploadImageUtils.getPath(this, selectedImage);
Uri uri = Uri.parse("file://" + picturePath);
ChatUtil.sendImaMessage(IChat.CHATROOM, roomIdOne, uri, uri, sendMessageListener);
break;
default:
break;
}
}
}
private IChat.OnConnectListener connectListener = new IChat.OnConnectListener() {
@Override
public void onTokenIncorrect(String s) {
Log.e(TAG, "ConnectListener TokenIncorrect");
}
@Override
public void onSuccess(final String s) {
Log.e(TAG, "ConnectListener 连接监听" + s);
}
@Override
public void onError(int i, final String s) {
Log.e(TAG, "ConnectListener errorCode : " + i + " : errorMessage : " + s);
}
};
@Override
public void onItemClick(VoiceMessage voiceMessage) {
if (voiceMessage.isUserSend()) {
playerUtil.start(voiceMessage.getCnVoiceMessage().getVoiceUri());
} else {
final String voicePath = FileUtil.getTempFile(FileUtil.FileType.AUDIO).getAbsolutePath();
voiceMessage.getCnVoiceMessage().getVoice(voicePath, new IChat.OnDownloadListener() {
@Override
public void onSuccess() {
if (playerUtil != null)
playerUtil.start(Uri.parse(voicePath));
}
@Override
public void onError(int i, String s) {
}
});
}
}
/**************************************************************************/
/**
* 开启扫描之前判断权限是否打开
*/
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)
) {
StartListener();
//判断是否开启语音权限
} else {
//请求获取摄像头权限
ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO}, 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(ChatRoomActivity.this, "没有麦克风权限,请前往“设置 - 应用 - 权限”中开启权限", Toast.LENGTH_SHORT).show();
} else if (lacksPermission(PERMISSIONS[1])) {
Toast.makeText(ChatRoomActivity.this, "没有文件读写权限,请前往“设置 - 应用 - 权限”中开启权限", Toast.LENGTH_SHORT).show();
}
} else {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPop.showAtLocation(re_chat, 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(ChatRoomActivity.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(ChatRoomActivity.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.CHATROOM, roomIdOne, 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);
send_messageOneBtn.setVisibility(View.VISIBLE);
} else {
send_messageOneBtn.setVisibility(View.GONE);
ima_send.setVisibility(View.VISIBLE);
}
}
};
}