Repository navigation
Expand file tree
/
Copy pathChatActivity.java
More file actions
1261 lines (1087 loc) · 57.7 KB
/
Copy pathChatActivity.java
File metadata and controls
1261 lines (1087 loc) · 57.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
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.example.wmchat2026;
import android.util.Log;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.*;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.bumptech.glide.Glide;
import android.view.ViewGroup;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ChatActivity extends Activity {
private ListView lvChat;
private EditText edtMessage, edtDebug;
private Button btnSend, btnRecord, btnAdd;
private LinearLayout layoutRecording;
private TextView txtRecordingTime;
private Button btnStopRecord, btnCancelRecord;
private String friendName;
private final List<HashMap<String, Object>> chatList = new ArrayList<>();
private ChatAdapter adapter;
private final Handler handler = new Handler(android.os.Looper.getMainLooper());
private final ExecutorService downloadQueue = Executors.newSingleThreadExecutor();
private final Map<String, Integer> downloadProgressMap = Collections.synchronizedMap(new HashMap<>());
private final int REQUEST_PERMISSION_CODE = 1000;
private final int REQUEST_IMAGE_PICK = 1001;
// WAV 录音
private AudioRecord audioRecord;
private volatile boolean isRecording = false;
private String audioFilePath; // path without extension, we'll append .pcm/.wav
private final int SAMPLE_RATE = 16000;
private final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
private final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
private MediaPlayer mediaPlayer;
private static final String TAG = "ChatActivity";
// =================== 来电检测相关 ===================
private final Handler callHandler = new Handler();
private Runnable callCheckRunnable;
private final int CALL_CHECK_INTERVAL = 3000; // 每3秒轮询一次
private boolean incomingDialogVisible = false; // 避免重复弹窗
private String incomingCaller = null; // 当前显示弹窗的 caller
// ==================================================
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
friendName = getIntent().getStringExtra("friend");
layoutCalling = findViewById(R.id.layoutCalling);
txtCallingStatus = findViewById(R.id.txtCallingStatus);
btnCancelCall = findViewById(R.id.btnCancelCall);
if (layoutCalling != null) layoutCalling.setVisibility(View.GONE);
if (btnCancelCall != null) btnCancelCall.setOnClickListener(v -> cancelCall());
lvChat = findViewById(R.id.lvChat);
edtMessage = findViewById(R.id.edtMessage);
edtDebug = findViewById(R.id.edtDebug);
btnSend = findViewById(R.id.btnSend);
btnRecord = findViewById(R.id.btnRecord);
btnAdd = findViewById(R.id.btnAdd);
layoutRecording = findViewById(R.id.layoutRecording);
txtRecordingTime = findViewById(R.id.txtRecordingTime);
btnStopRecord = findViewById(R.id.btnStopRecord);
btnCancelRecord = findViewById(R.id.btnCancelRecord);
if (edtDebug != null) edtDebug.setKeyListener(null);
adapter = new ChatAdapter();
if (lvChat != null) lvChat.setAdapter(adapter);
// 文本发送按钮
if (btnSend != null && edtMessage != null) {
btnSend.setEnabled(false);
edtMessage.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {
btnSend.setEnabled(s.toString().trim().length() > 0);
}
@Override public void afterTextChanged(Editable s) {}
});
btnSend.setOnClickListener(v -> {
String txt = edtMessage.getText() == null ? "" : edtMessage.getText().toString().trim();
if (!txt.isEmpty()) sendTextMessage(txt);
});
}
// 录音按钮
if (btnRecord != null) btnRecord.setOnClickListener(v -> checkPermissionsAndStartRecording());
if (btnStopRecord != null) btnStopRecord.setOnClickListener(v -> stopRecordingAndSendUI());
if (btnCancelRecord != null) btnCancelRecord.setOnClickListener(v -> cancelRecordingUI());
// 加号按钮
if (btnAdd != null) btnAdd.setOnClickListener(v -> showAddMenu());
// 初始化录音区隐藏
if (layoutRecording != null) layoutRecording.setVisibility(View.GONE);
loadMessages();
// 启动来电轮询(在聊天界面打开时检查是否有来电)
startVoiceCallCheck();
}
@Override
protected void onPause() {
super.onPause();
stopVoiceCallCheck();
stopRecording(false);
releaseMediaPlayer();
}
@Override
protected void onDestroy() {
super.onDestroy();
stopVoiceCallCheck();
stopRecording(false);
downloadQueue.shutdownNow();
releaseMediaPlayer();
}
private void debug(final String text) {
// 1) 始终把信息写到 Logcat,便于排查(即使 UI 不可用)
Log.d(TAG, text == null ? "null" : text);
// 2) 安全地在主线程更新 edtDebug(若存在)
handler.post(() -> {
try {
if (edtDebug != null) {
// 确保可见(避免被 GONE / INVISIBLE 覆盖住)
if (edtDebug.getVisibility() != View.VISIBLE) edtDebug.setVisibility(View.VISIBLE);
// 附加文本并滚到底部
edtDebug.append((text == null ? "null" : text) + "\n\n");
edtDebug.setSelection(edtDebug.getText().length());
} else {
// 如果 edtDebug 为 null,我们把一条指示也记录到 Logcat(不会抛)
Log.w(TAG, "edtDebug is null — cannot write debug UI");
}
} catch (Throwable t) {
// 避免 UI 写入抛异常导致更严重问题,记录并继续
Log.e(TAG, "debug UI append failed", t);
}
});
}
// =================== 加号菜单功能 ===================
private void showAddMenu() {
if (btnAdd == null) return;
PopupMenu menu = new PopupMenu(this, btnAdd);
menu.getMenu().add("发送图片");
menu.getMenu().add("拨打电话"); // ✅ 新增拨打电话选项
menu.setOnMenuItemClickListener(item -> {
String title = item.getTitle().toString();
if ("发送图片".equals(title)) {
pickImageFromGallery();
return true;
} else if ("拨打电话".equals(title)) {
if (friendName == null || friendName.trim().isEmpty()) {
Toast.makeText(ChatActivity.this, "好友名称为空,无法拨打", Toast.LENGTH_SHORT).show();
return true;
}
startCall(friendName); // 调用已有呼叫逻辑
return true;
}
return false;
});
menu.show();
}
private void pickImageFromGallery() {
try {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_IMAGE_PICK);
} catch (Exception e) {
debug("打开相册失败: " + e.getMessage());
Toast.makeText(this, "无法打开相册", Toast.LENGTH_SHORT).show();
}
}
private void startCall(String callee) {
// ✅立刻进入“正在呼叫”状态
isCalling = true;
currentCallee = callee;
// ✅显示呼叫界面
if (layoutCalling != null) {
layoutCalling.setVisibility(View.VISIBLE);
}
if (txtCallingStatus != null) {
txtCallingStatus.setText("正在呼叫 " + callee + "...");
}
new Thread(() -> {
try {
String postData =
"token=" + URLEncoder.encode(Session.token, "UTF-8") +
"&to=" + URLEncoder.encode(callee, "UTF-8");
String raw = ApiClient.postRaw(
"http://wm.51ezu.com/wechat.php?action=start_call",
postData
);
debug("start_call 原始返回: " + raw);
JSONObject res = new JSONObject(raw);
if (res.optInt("code") == 200) {
// ✅开始轮询状态
handler.post(() -> {
Toast.makeText(ChatActivity.this,
"呼叫请求已发送,等待对方接听...",
Toast.LENGTH_SHORT).show();
startCallStatusCheck();
});
} else {
handler.post(() -> {
Toast.makeText(ChatActivity.this,
"呼叫失败: " + res.optString("msg"),
Toast.LENGTH_LONG).show();
// ❌失败要关闭 UI
endCallUI();
});
}
} catch (Exception e) {
debug("呼叫异常: " + e.getMessage());
handler.post(() -> {
Toast.makeText(ChatActivity.this,
"呼叫异常: " + e.getMessage(),
Toast.LENGTH_LONG).show();
endCallUI();
});
}
}).start();
}
private void startCallStatusCheck() {
stopCallStatusCheck();
callStatusRunnable = new Runnable() {
@Override
public void run() {
checkCallStatus();
callStatusHandler.postDelayed(this, CALL_STATUS_INTERVAL);
}
};
callStatusHandler.post(callStatusRunnable);
}
private void stopCallStatusCheck() {
if (callStatusRunnable != null) callStatusHandler.removeCallbacks(callStatusRunnable);
}
private void checkCallStatus() {
if (!isCalling || currentCallee == null || Session.token == null) return;
new Thread(() -> {
try {
String url = "http://wm.51ezu.com/wechat.php?action=call_status&token=" +
URLEncoder.encode(Session.token, "UTF-8") +
"&to=" + URLEncoder.encode(currentCallee, "UTF-8");
JSONObject res = ApiClient.get(url);
if (res != null && res.optInt("code") == 200) {
String status = res.optJSONObject("data").optString("status", "none");
handler.post(() -> {
if ("accepted".equals(status)) {
if (txtCallingStatus != null) txtCallingStatus.setText(currentCallee + " 已接听");
// TODO: 可以直接进入通话界面或播放通话音频
stopCallStatusCheck();
} else if ("rejected".equals(status) || "ended".equals(status)) {
Toast.makeText(ChatActivity.this, currentCallee + " 拒绝或挂断", Toast.LENGTH_SHORT).show();
endCallUI();
} else {
if (txtCallingStatus != null) txtCallingStatus.setText("正在呼叫 " + currentCallee + "...");
}
});
}
} catch (Exception e) {
debug("轮询呼叫状态异常: " + e.getMessage());
}
}).start();
}
private void cancelCall() {
if (!isCalling || currentCallee == null) return;
new Thread(() -> {
try {
String postData = "token=" + URLEncoder.encode(Session.token, "UTF-8") +
"&to=" + URLEncoder.encode(currentCallee, "UTF-8");
ApiClient.postJson("http://wm.51ezu.com/wechat.php?action=end_call", postData);
} catch (Exception e) { debug("取消呼叫异常: " + e.getMessage()); }
}).start();
endCallUI();
}
private void endCallUI() {
stopCallStatusCheck();
isCalling = false;
currentCallee = null;
if (layoutCalling != null) layoutCalling.setVisibility(View.GONE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
if (imageUri != null) uploadImage(imageUri);
}
}
private void uploadImage(Uri uri) {
new Thread(() -> {
InputStream is = null;
FileOutputStream fos = null;
try {
is = getContentResolver().openInputStream(uri);
if (is == null) throw new IOException("无法读取图片流");
File dir = getExternalFilesDir("WMCHAT_UPLOAD");
if (dir == null) dir = getCacheDir();
if (!dir.exists()) dir.mkdirs();
File file = new File(dir, "img_" + System.currentTimeMillis() + ".jpg");
fos = new FileOutputStream(file);
byte[] tmp = new byte[8192];
int r;
while ((r = is.read(tmp)) != -1) fos.write(tmp, 0, r);
fos.flush();
String boundary = "----WMCHATBoundary" + System.currentTimeMillis();
URL url = new URL("http://wm.51ezu.com/wechat.php?action=send_message");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// token
dos.writeBytes("--" + boundary + "\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"token\"\r\n\r\n");
dos.writeBytes(safeString(Session.token) + "\r\n");
// to
dos.writeBytes("--" + boundary + "\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"to\"\r\n\r\n");
dos.writeBytes(safeString(friendName) + "\r\n");
// image
dos.writeBytes("--" + boundary + "\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"image\"; filename=\"" + file.getName() + "\"\r\n");
dos.writeBytes("Content-Type: image/jpeg\r\n\r\n");
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
int len;
while ((len = fis.read(buffer)) != -1) dos.write(buffer, 0, len);
fis.close();
dos.writeBytes("\r\n--" + boundary + "--\r\n");
dos.flush();
dos.close();
int respCode = conn.getResponseCode();
InputStream resp = (respCode >= 400) ? conn.getErrorStream() : conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] rb = new byte[4096];
int rl;
while (resp != null && (rl = resp.read(rb)) != -1) baos.write(rb, 0, rl);
if (resp != null) resp.close();
debug("图片发送结果: HTTP " + respCode + " -> " + new String(baos.toByteArray()));
// 刷新消息
loadMessages();
} catch (Exception e) {
debug("图片上传异常: " + e.getMessage());
} finally {
try { if (is != null) is.close(); } catch (Exception ignored) {}
try { if (fos != null) fos.close(); } catch (Exception ignored) {}
}
}).start();
}
// =================== 文本发送 ===================
private void sendTextMessage(final String msg) {
if (msg == null || msg.trim().isEmpty()) return;
if (edtMessage != null) edtMessage.setText("");
new Thread(() -> {
try {
String postData = "token=" + URLEncoder.encode(safeString(Session.token), "UTF-8") +
"&to=" + URLEncoder.encode(safeString(friendName), "UTF-8") +
"&text=" + URLEncoder.encode(msg, "UTF-8");
ApiClient.post("http://wm.51ezu.com/wechat.php?action=send_message", postData);
loadMessages();
} catch (Exception e) { debug("发送异常:" + e.getMessage()); }
}).start();
}
// =================== 录音与播放(改写部分) ===================
private void checkPermissionsAndStartRecording() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
List<String> perms = new ArrayList<>();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED)
perms.add(Manifest.permission.RECORD_AUDIO);
if (!perms.isEmpty()) {
ActivityCompat.requestPermissions(this, perms.toArray(new String[0]), REQUEST_PERMISSION_CODE);
return;
}
}
startRecordingUI();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_PERMISSION_CODE) {
boolean ok = true;
for (int res : grantResults) {
if (res != PackageManager.PERMISSION_GRANTED) { ok = false; break; }
}
if (ok) startRecordingUI();
else Toast.makeText(this, "需要录音权限才能录音", Toast.LENGTH_SHORT).show();
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
// =================== 录音控制(带实时计时) ===================
private long recordStartTime = 0L;
private Runnable recordTimeRunnable;
private void startRecordingUI() {
if (layoutRecording != null) layoutRecording.setVisibility(View.VISIBLE);
startRecording();
}
private void cancelRecordingUI() {
if (layoutRecording != null) layoutRecording.setVisibility(View.GONE);
stopRecording(false);
}
private void stopRecordingAndSendUI() {
if (layoutRecording != null) layoutRecording.setVisibility(View.GONE);
stopRecording(true);
}
private void startRecording() {
if (isRecording) return;
try {
// 文件路径
File dir = getExternalFilesDir("WMCHAT_VOICE");
if (dir == null) dir = getCacheDir();
if (!dir.exists()) dir.mkdirs();
audioFilePath = new File(dir, "voice_" + System.currentTimeMillis() + ".wav").getAbsolutePath();
// AudioRecord 初始化
int minBuf = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);
if (minBuf <= 0) minBuf = SAMPLE_RATE * 2;
int bufferSize = Math.max(minBuf, SAMPLE_RATE * 4);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT, bufferSize);
if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
debug("AudioRecord 初始化失败");
try { audioRecord.release(); } catch (Exception ignored) {}
audioRecord = null;
return;
}
audioRecord.startRecording();
isRecording = true;
recordStartTime = System.currentTimeMillis();
// ===== 启动录音时长计时 =====
recordTimeRunnable = new Runnable() {
@Override
public void run() {
if (isRecording) {
long elapsed = System.currentTimeMillis() - recordStartTime;
int sec = (int) (elapsed / 1000);
if (txtRecordingTime != null) txtRecordingTime.setText(formatDuration(sec));
handler.postDelayed(this, 500); // 每 0.5 秒刷新
} else {
if (txtRecordingTime != null) txtRecordingTime.setText("0:00");
}
}
};
handler.post(recordTimeRunnable);
// ===== 启动录音线程 =====
final int finalBufferSize = bufferSize;
new Thread(() -> {
try (FileOutputStream fos = new FileOutputStream(audioFilePath + ".pcm")) {
byte[] data = new byte[finalBufferSize];
while (isRecording) {
int read = audioRecord.read(data, 0, data.length);
if (read > 0) fos.write(data, 0, read);
}
fos.flush();
} catch (Exception e) {
debug("录音线程异常: " + e.getMessage());
}
}, "WMCHAT-Recorder").start();
} catch (Exception e) {
debug("启动录音失败: " + e.getMessage());
}
}
private void stopRecording(boolean send) {
if (!isRecording && audioRecord == null) return;
// 停止计时
if (recordTimeRunnable != null) handler.removeCallbacks(recordTimeRunnable);
if (txtRecordingTime != null) txtRecordingTime.setText("0:00");
try {
isRecording = false;
if (audioRecord != null) {
try { audioRecord.stop(); } catch (Exception ignored) {}
try { audioRecord.release(); } catch (Exception ignored) {}
audioRecord = null;
}
if (send) {
File pcmFile = new File(audioFilePath + ".pcm");
File wavFile = new File(audioFilePath);
if (pcmFile.exists() && pcmFile.length() > 0) {
rawToWave(pcmFile, wavFile);
pcmFile.delete();
sendVoiceWav(wavFile);
} else debug("无有效PCM文件,未发送语音");
}
} catch (Exception e) {
debug("停止录音异常: " + e.getMessage());
}
}
private void rawToWave(File pcmFile, File wavFile) {
try (FileInputStream fis = new FileInputStream(pcmFile);
FileOutputStream fos = new FileOutputStream(wavFile)) {
long totalAudioLen = fis.getChannel().size();
long totalDataLen = totalAudioLen + 36;
int channels = 1;
long byteRate = 16L * SAMPLE_RATE * channels / 8L;
writeWaveFileHeader(fos, totalAudioLen, totalDataLen, SAMPLE_RATE, channels, byteRate);
byte[] buffer = new byte[8192];
int read;
while ((read = fis.read(buffer)) != -1) fos.write(buffer, 0, read);
fos.flush();
} catch (Exception e) {
debug("WAV 转换失败: " + e.getMessage());
}
}
private void writeWaveFileHeader(FileOutputStream out, long totalAudioLen, long totalDataLen,
int sampleRate, int channels, long byteRate) throws IOException {
byte[] header = new byte[44];
header[0] = 'R'; header[1] = 'I'; header[2] = 'F'; header[3] = 'F';
header[4] = (byte) (totalDataLen & 0xff);
header[5] = (byte) ((totalDataLen >> 8) & 0xff);
header[6] = (byte) ((totalDataLen >> 16) & 0xff);
header[7] = (byte) ((totalDataLen >> 24) & 0xff);
header[8] = 'W'; header[9] = 'A'; header[10] = 'V'; header[11] = 'E';
header[12] = 'f'; header[13] = 'm'; header[14] = 't'; header[15] = ' ';
header[16] = 16; header[17] = 0; header[18] = 0; header[19] = 0;
header[20] = 1; header[21] = 0;
header[22] = (byte) channels; header[23] = 0;
header[24] = (byte) (sampleRate & 0xff);
header[25] = (byte) ((sampleRate >> 8) & 0xff);
header[26] = (byte) ((sampleRate >> 16) & 0xff);
header[27] = (byte) ((sampleRate >> 24) & 0xff);
header[28] = (byte) (byteRate & 0xff);
header[29] = (byte) ((byteRate >> 8) & 0xff);
header[30] = (byte) ((byteRate >> 16) & 0xff);
header[31] = (byte) ((byteRate >> 24) & 0xff);
header[32] = (byte) (2 * channels); header[33] = 0;
header[34] = 16; header[35] = 0;
header[36] = 'd'; header[37] = 'a'; header[38] = 't'; header[39] = 'a';
header[40] = (byte) (totalAudioLen & 0xff);
header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
header[43] = (byte) ((totalAudioLen >> 24) & 0xff);
out.write(header, 0, 44);
}
private void sendVoiceWav(File wavFile) {
new Thread(() -> {
try {
String boundary = "----WMCHATBoundary" + System.currentTimeMillis();
URL url = new URL("http://wm.51ezu.com/wechat.php?action=send_message");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// token
dos.writeBytes("--" + boundary + "\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"token\"\r\n\r\n");
dos.writeBytes(safeString(Session.token) + "\r\n");
// to
dos.writeBytes("--" + boundary + "\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"to\"\r\n\r\n");
dos.writeBytes(safeString(friendName) + "\r\n");
// audio
dos.writeBytes("--" + boundary + "\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"audio\"; filename=\"" + wavFile.getName() + "\"\r\n");
dos.writeBytes("Content-Type: audio/wav\r\n\r\n");
FileInputStream fis = new FileInputStream(wavFile);
byte[] buffer = new byte[4096];
int len;
while ((len = fis.read(buffer)) != -1) dos.write(buffer, 0, len);
fis.close();
dos.writeBytes("\r\n--" + boundary + "--\r\n");
dos.flush();
dos.close();
int respCode = conn.getResponseCode();
InputStream resp = (respCode >= 400) ? conn.getErrorStream() : conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (resp != null) {
while ((len = resp.read(buffer)) != -1) baos.write(buffer, 0, len);
resp.close();
}
debug("语音发送结果: HTTP " + respCode + " -> " + new String(baos.toByteArray()));
loadMessages();
} catch (Exception e) { debug("语音上传异常: " + e.getMessage()); }
}).start();
}
// =================== 消息加载相关(保持逻辑) ===================
private void loadMessages() {
if (friendName == null || Session.token == null) return;
new Thread(() -> {
try {
String url = "http://wm.51ezu.com/wechat.php?action=get_messages&token=" +
URLEncoder.encode(safeString(Session.token), "UTF-8") +
"&with=" + URLEncoder.encode(safeString(friendName), "UTF-8");
JSONObject res = ApiClient.get(url);
if (res != null && res.optInt("code") == 200) {
synchronized (chatList) {
chatList.clear();
JSONObject dataObj = res.optJSONObject("data");
if (dataObj != null) {
JSONArray msgs = dataObj.optJSONArray("messages");
if (msgs != null) {
for (int i = 0; i < msgs.length(); i++) addMessageToList(msgs.getJSONObject(i));
}
}
}
handler.post(() -> {
adapter.notifyDataSetChanged();
if (lvChat != null && chatList.size() > 0) lvChat.setSelection(chatList.size() - 1);
});
} else {
debug("get_messages 返回异常: " + (res != null ? res.toString() : "null"));
}
} catch (Exception e) { debug("加载异常:" + e.getMessage()); }
}).start();
}
private void addMessageToList(JSONObject m) {
HashMap<String, Object> map = new HashMap<>();
String type = m.optString("type", "text");
String rawMessage = m.optString("message", "");
map.put("from", m.optString("from"));
map.put("type", type);
map.put("message", rawMessage);
String url = m.optString("url", rawMessage);
if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) map.put("url", url);
else map.put("url", "");
map.put("duration", m.optInt("duration", 0));
chatList.add(map);
}
private String safeString(Object obj) { return obj == null ? "" : obj.toString(); }
private int safeInt(Object obj) { if (obj instanceof Number) return ((Number)obj).intValue(); return 0; }
private String formatDuration(int sec) { return (sec / 60) + ":" + String.format("%02d", sec % 60); }
// =================== 适配器 ===================
private class ChatAdapter extends BaseAdapter {
@Override public int getCount() { return chatList.size(); }
@Override public Object getItem(int position) { return chatList.get(position); }
@Override public long getItemId(int position) { return position; }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.item_chat, parent, false);
vh = new ViewHolder();
vh.layoutLeft = convertView.findViewById(R.id.layoutLeft);
vh.layoutRight = convertView.findViewById(R.id.layoutRight);
vh.txtFromLeft = convertView.findViewById(R.id.txtFromLeft);
vh.txtAudioLeft = convertView.findViewById(R.id.txtAudioLeft);
vh.txtMessageLeft = convertView.findViewById(R.id.txtMessageLeft);
vh.imgContentLeft = convertView.findViewById(R.id.imgContentLeft);
vh.txtFromRight = convertView.findViewById(R.id.txtFromRight);
vh.txtAudioRight = convertView.findViewById(R.id.txtAudioRight);
vh.txtMessageRight = convertView.findViewById(R.id.txtMessageRight);
vh.imgContentRight = convertView.findViewById(R.id.imgContentRight);
vh.pbLeft = convertView.findViewById(R.id.pbDownloadLeft);
vh.pbRight = convertView.findViewById(R.id.pbDownloadRight);
convertView.setTag(vh);
} else { vh = (ViewHolder) convertView.getTag(); }
HashMap<String, Object> item = chatList.get(position);
String from = safeString(item.get("from"));
String type = safeString(item.get("type"));
String url = safeString(item.get("url"));
int dur = safeInt(item.get("duration"));
boolean isMe = from.equals(safeString(Session.username));
if (vh.layoutLeft != null) vh.layoutLeft.setVisibility(View.GONE);
if (vh.layoutRight != null) vh.layoutRight.setVisibility(View.GONE);
Integer progress = (url.isEmpty() ? null : downloadProgressMap.get(url));
try {
if (isMe) {
if (vh.layoutRight != null) vh.layoutRight.setVisibility(View.VISIBLE);
if (vh.txtFromRight != null) vh.txtFromRight.setText(from);
if (vh.txtMessageRight != null) vh.txtMessageRight.setVisibility("text".equals(type) ? View.VISIBLE : View.GONE);
if (vh.imgContentRight != null) vh.imgContentRight.setVisibility("image".equals(type) ? View.VISIBLE : View.GONE);
if (vh.txtAudioRight != null) vh.txtAudioRight.setVisibility("audio".equals(type) ? View.VISIBLE : View.GONE);
if ("text".equals(type) && vh.txtMessageRight != null) vh.txtMessageRight.setText(safeString(item.get("message")));
if ("image".equals(type) && vh.imgContentRight != null) {
if (!url.isEmpty()) Glide.with(ChatActivity.this).load(url).into(vh.imgContentRight);
else vh.imgContentRight.setImageResource(android.R.drawable.ic_menu_report_image);
}
if ("audio".equals(type) && vh.txtAudioRight != null) {
if (progress != null) {
vh.txtAudioRight.setText("下载中 " + progress + "%");
if (vh.pbRight != null) { vh.pbRight.setVisibility(View.VISIBLE); vh.pbRight.setProgress(progress); }
} else {
vh.txtAudioRight.setText(dur <= 0 ? "点击加载" : "语音 " + formatDuration(dur));
if (vh.pbRight != null) vh.pbRight.setVisibility(View.GONE);
}
final String audioUrl = url;
vh.txtAudioRight.setOnClickListener(v -> downloadAndPlayAudio(audioUrl, position));
}
} else {
if (vh.layoutLeft != null) vh.layoutLeft.setVisibility(View.VISIBLE);
if (vh.txtFromLeft != null) vh.txtFromLeft.setText(from);
if (vh.txtMessageLeft != null) vh.txtMessageLeft.setVisibility("text".equals(type) ? View.VISIBLE : View.GONE);
if (vh.imgContentLeft != null) vh.imgContentLeft.setVisibility("image".equals(type) ? View.VISIBLE : View.GONE);
if (vh.txtAudioLeft != null) vh.txtAudioLeft.setVisibility("audio".equals(type) ? View.VISIBLE : View.GONE);
if ("text".equals(type) && vh.txtMessageLeft != null) vh.txtMessageLeft.setText(safeString(item.get("message")));
if ("image".equals(type) && vh.imgContentLeft != null) {
if (!url.isEmpty()) Glide.with(ChatActivity.this).load(url).into(vh.imgContentLeft);
else vh.imgContentLeft.setImageResource(android.R.drawable.ic_menu_report_image);
}
if ("audio".equals(type) && vh.txtAudioLeft != null) {
if (progress != null) {
vh.txtAudioLeft.setText("下载中 " + progress + "%");
if (vh.pbLeft != null) { vh.pbLeft.setVisibility(View.VISIBLE); vh.pbLeft.setProgress(progress); }
} else {
vh.txtAudioLeft.setText(dur <= 0 ? "点击加载" : "语音 " + formatDuration(dur));
if (vh.pbLeft != null) vh.pbLeft.setVisibility(View.GONE);
}
final String audioUrl = url;
vh.txtAudioLeft.setOnClickListener(v -> downloadAndPlayAudio(audioUrl, position));
}
}
} catch (Exception e) {
debug("渲染消息视图出错: " + e.getMessage());
}
return convertView;
}
class ViewHolder {
LinearLayout layoutLeft, layoutRight;
TextView txtFromLeft, txtAudioLeft, txtMessageLeft, txtFromRight, txtAudioRight, txtMessageRight;
ImageView imgContentLeft, imgContentRight;
ProgressBar pbLeft, pbRight;
}
}
// =================== 音频下载与播放(改写) ===================
private void downloadAndPlayAudio(String audioUrl, final int position) {
if (audioUrl == null || audioUrl.trim().isEmpty()) return;
// 初始化下载进度
downloadProgressMap.put(audioUrl, 0);
handler.post(() -> adapter.notifyDataSetChanged());
downloadQueue.execute(() -> {
try {
// 缓存目录
File cacheDir = getExternalFilesDir("WMCHAT_CACHE");
if (cacheDir == null) cacheDir = getCacheDir();
if (cacheDir != null && !cacheDir.exists()) cacheDir.mkdirs();
// 使用唯一文件名,避免冲突
String fileName = "cache_" + System.currentTimeMillis() + "_" + Math.abs(audioUrl.hashCode()) + ".wav";
File localFile = new File(cacheDir, fileName);
// 下载音频(若文件已存在且大小合理,则跳过)
if (!localFile.exists() || localFile.length() < 100) {
HttpURLConnection conn = (HttpURLConnection) new URL(audioUrl).openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(15000);
int total = conn.getContentLength();
InputStream is = conn.getInputStream();
try (FileOutputStream fos = new FileOutputStream(localFile)) {
byte[] buffer = new byte[4096];
int len;
int written = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
written += len;
if (total > 0) {
int prog = (int) (written * 100L / total);
downloadProgressMap.put(audioUrl, prog);
handler.post(() -> adapter.notifyDataSetChanged());
}
}
fos.flush();
} finally {
try { if (is != null) is.close(); } catch (Exception ignored) {}
}
}
// 解析 WAV 时长并更新消息列表
int durationSec = getWavDuration(localFile);
synchronized (chatList) {
if (position >= 0 && position < chatList.size()) chatList.get(position).put("duration", durationSec);
}
// 在 UI 线程播放音频
handler.post(() -> {
downloadProgressMap.remove(audioUrl);
adapter.notifyDataSetChanged();
playAudioFile(localFile);
});
} catch (Exception e) {
handler.post(() -> {
downloadProgressMap.remove(audioUrl);
adapter.notifyDataSetChanged();
});
debug("下载音频异常: " + e.getMessage());
}
});
}
/**
* 使用独立 MediaPlayer 播放音频文件
* 播放结束自动释放,支持连续播放多个音频
*/
private void playAudioFile(final File file) {
if (file == null || !file.exists()) {
debug("播放文件不存在: " + (file == null ? "null" : file.getAbsolutePath()));
return;
}
handler.post(() -> {
try {
// 先释放上一个(如果需要)
releaseMediaPlayer();
MediaPlayer mp = new MediaPlayer();
mediaPlayer = mp; // 保存引用以便整体控制/释放
FileInputStream fis = new FileInputStream(file);
mp.setDataSource(fis.getFD());
fis.close();
mp.setOnPreparedListener(mediaPlayer1 -> mediaPlayer1.start());
mp.setOnCompletionListener(mediaPlayer1 -> {
try { mediaPlayer1.release(); } catch (Exception ignored) {}
if (mediaPlayer == mediaPlayer1) mediaPlayer = null;
handler.post(() -> adapter.notifyDataSetChanged());
});
mp.setOnErrorListener((mediaPlayer1, what, extra) -> {
debug("MediaPlayer 播放错误 what=" + what + " extra=" + extra + " file=" + file.getName());
try { mediaPlayer1.release(); } catch (Exception ignored) {}
if (mediaPlayer == mediaPlayer1) mediaPlayer = null;
return true;
});
mp.prepareAsync(); // 在 UI 线程异步准备
handler.post(() -> adapter.notifyDataSetChanged());
} catch (Exception e) {
debug("播放失败(UI 线程): " + e.getMessage());
try { if (mediaPlayer != null) { mediaPlayer.release(); mediaPlayer = null; } } catch (Exception ignored) {}
}
});
}
// 解析 WAV 文件时长(秒)
private int getWavDuration(File file) {
try (FileInputStream fis = new FileInputStream(file)) {
byte[] header = new byte[44];
if (fis.read(header) != 44) return 0;
int byteRate = ((header[28] & 0xff) | ((header[29] & 0xff) << 8) | ((header[30] & 0xff) << 16) | ((header[31] & 0xff) << 24));
int dataSize = ((header[40] & 0xff) | ((header[41] & 0xff) << 8) | ((header[42] & 0xff) << 16) | ((header[43] & 0xff) << 24));
if (byteRate > 0) return dataSize / byteRate;
} catch (Exception ignored) {}
return 0;
}
private void releaseMediaPlayer() {
try {
if (mediaPlayer != null) {
try { mediaPlayer.stop(); } catch (Exception ignored) {}
try { mediaPlayer.release(); } catch (Exception ignored) {}
mediaPlayer = null;
}
} catch (Exception ignored) {}
}
// =================== 来电检测实现 ===================
// =================== 来电轮询 ===================
// 启动轮询
// 启动轮询(替换原有 startVoiceCallCheck 实现)
// 调用位置:onCreate() 中已经有 startVoiceCallCheck();
private void startVoiceCallCheck() {
stopVoiceCallCheck(); // 先停止已有的,防止重复
Log.d(TAG, "startVoiceCallCheck() called; Session.token=" + Session.token);
callCheckRunnable = new Runnable() {
@Override
public void run() {
Log.d(TAG, "callCheckRunnable posted -> spawn network thread");
new Thread(() -> {
HttpURLConnection conn = null;
try {
// ---- quick token check (we still schedule next poll in finally) ----
if (Session.token == null || Session.token.trim().isEmpty()) {
Log.d(TAG, "startVoiceCallCheck: token is null/empty - will retry later");
return;
}
String urlStr = "http://wm.51ezu.com/wechat.php?action=voice_call_status&token="
+ URLEncoder.encode(Session.token, "UTF-8");
Log.d(TAG, "voice_check url=" + urlStr);
conn = (HttpURLConnection) new URL(urlStr).openConnection();