android中的Manifest.permission红色解决

本文探讨了从标准Java开发转向Android开发时,如何正确修改Manifest导入语句,确保应用程序能够顺利运行。通过实例演示了将'import java.util.jar.Manifest;'更改为'import android.Manifest;'的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.jar.Manifest;

改成

import android.Manifest;

package com.example.ball.ui.activity; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.util.Size; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.camera.core.CameraSelector; import androidx.camera.core.ImageAnalysis; import androidx.camera.core.ImageProxy; import androidx.camera.core.Preview; import androidx.camera.lifecycle.ProcessCameraProvider; import androidx.camera.view.PreviewView; import androidx.core.content.ContextCompat; import com.example.ball.R; import com.google.common.util.concurrent.ListenableFuture; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CameraActivity extends AppCompatActivity { private static final String TAG = "ColorRecognition"; private static final int SAMPLE_SIZE = 5; // 采样区域半径 private static final int COLOR_TOLERANCE = 80; // 颜色匹配容差 // 预设的10种颜色及其名称 private static final Map<Integer, String> PRESET_COLORS = new HashMap<Integer, String>() {{ put(Color.RED, "红色"); put(Color.GREEN, "绿色"); put(Color.BLUE, "蓝色"); put(Color.YELLOW, "黄色"); put(Color.CYAN, "青色"); put(Color.MAGENTA, "品红"); put(0xFFFFA500, "橙色"); // 橙色 put(0xFF800080, "紫色"); // 紫色 put(0xFFFFC0CB, "粉色"); // 粉色 put(0xFFA52A2A, "棕色"); // 棕色 }}; private PreviewView previewView; private View targetArea; private View colorPreview; private TextView tvColorName; private TextView tvColorInfo; private TextView tvDetectionStatus; private ExecutorService cameraExecutor; private int targetX = 0; // 目标区域中心X坐标 private int targetY = 0; // 目标区域中心Y坐标 @RequiresApi(api = Build.VERSION_CODES.M) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); previewView = findViewById(R.id.previewView); targetArea = findViewById(R.id.targetArea); colorPreview = findViewById(R.id.colorPreview); tvColorName = findViewById(R.id.tvColorName); tvColorInfo = findViewById(R.id.tvColorInfo); tvDetectionStatus = findViewById(R.id.tvDetectionStatus); cameraExecutor = Executors.newSingleThreadExecutor(); // 设置目标区域位置(屏幕中心) previewView.post(() -> { targetX = previewView.getWidth() / 2; targetY = previewView.getHeight() / 2; updateTargetPosition(); }); // 启动摄像头 if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) == android.content.pm.PackageManager.PERMISSION_GRANTED) { startCamera(); } else { requestPermissions(new String[]{android.Manifest.permission.CAMERA}, 1); } } private void updateTargetPosition() { targetArea.setX(targetX - targetArea.getWidth() / 2f); targetArea.setY(targetY - targetArea.getHeight() / 2f); } private void startCamera() { ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this); cameraProviderFuture.addListener(() -> { try { ProcessCameraProvider cameraProvider = cameraProviderFuture.get(); // 配置预览 Preview preview = new Preview.Builder().build(); preview.setSurfaceProvider(previewView.getSurfaceProvider()); // 配置图像分析 ImageAnalysis imageAnalysis = new ImageAnalysis.Builder() .setTargetResolution(new Size(640, 480)) // 优化性能 .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) .build(); imageAnalysis.setAnalyzer(cameraExecutor, new ColorAnalyzer()); // 选择后置摄像头 CameraSelector cameraSelector = new CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build(); // 绑定用例 cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis); } catch (ExecutionException | InterruptedException e) { Log.e(TAG, "Camera setup error: " + e.getMessage()); } }, ContextCompat.getMainExecutor(this)); } private class ColorAnalyzer implements ImageAnalysis.Analyzer { @Override public void analyze(@NonNull ImageProxy image) { // 坐标转换(预览坐标 → 图像坐标) int imgWidth = image.getWidth(); int imgHeight = image.getHeight(); int previewWidth = previewView.getWidth(); int previewHeight = previewView.getHeight(); int imgX = (int) (targetX * (imgWidth / (float) previewWidth)); int imgY = (int) (targetY * (imgHeight / (float) previewHeight)); // 从YUV数据提取颜色 int color = extractColor(image, imgX, imgY); // 更新UI runOnUiThread(() -> updateColorDisplay(color)); image.close(); } private int extractColor(ImageProxy image, int centerX, int centerY) { ImageProxy.PlaneProxy[] planes = image.getPlanes(); int rSum = 0, gSum = 0, bSum = 0; int count = 0; // 采样区域:中心点周围5x5像素 for (int dy = -SAMPLE_SIZE; dy <= SAMPLE_SIZE; dy++) { for (int dx = -SAMPLE_SIZE; dx <= SAMPLE_SIZE; dx++) { int x = centerX + dx; int y = centerY + dy; if (x >= 0 && x < image.getWidth() && y >= 0 && y < image.getHeight()) { int color = getRGBFromYUV(planes, x, y, image.getWidth()); rSum += Color.red(color); gSum += Color.green(color); bSum += Color.blue(color); count++; } } } // 计算平均颜色 if (count > 0) { return Color.rgb(rSum / count, gSum / count, bSum / count); } return Color.BLACK; } // 高效YUV转RGB private int getRGBFromYUV(ImageProxy.PlaneProxy[] planes, int x, int y, int width) { ByteBuffer yBuffer = planes[0].getBuffer(); ByteBuffer uBuffer = planes[1].getBuffer(); ByteBuffer vBuffer = planes[2].getBuffer(); // 计算偏移量 int yOffset = y * planes[0].getRowStride() + x * planes[0].getPixelStride(); int uvX = x / 2; int uvY = y / 2; int uOffset = uvY * planes[1].getRowStride() + uvX * planes[1].getPixelStride(); int vOffset = uvY * planes[2].getRowStride() + uvX * planes[2].getPixelStride(); // 获取YUV值 int yVal = yBuffer.get(yOffset) & 0xFF; int uVal = uBuffer.get(uOffset) & 0xFF; int vVal = vBuffer.get(vOffset) & 0xFF; // YUV转RGB公式 int r = clamp((int) (yVal + 1.402 * (vVal - 128))); int g = clamp((int) (yVal - 0.34414 * (uVal - 128) - 0.71414 * (vVal - 128))); int b = clamp((int) (yVal + 1.772 * (uVal - 128))); return Color.rgb(r, g, b); } private int clamp(int value) { return Math.max(0, Math.min(255, value)); } } private void updateColorDisplay(int detectedColor) { // 更新颜色预览 colorPreview.setBackgroundColor(detectedColor); // 获取RGB值 int r = Color.red(detectedColor); int g = Color.green(detectedColor); int b = Color.blue(detectedColor); String rgb = String.format("RGB: %d, %d, %d", r, g, b); tvColorInfo.setText(rgb); // 匹配预设颜色 String colorName = "未设定颜色"; for (Map.Entry<Integer, String> entry : PRESET_COLORS.entrySet()) { int presetColor = entry.getKey(); int pr = Color.red(presetColor); int pg = Color.green(presetColor); int pb = Color.blue(presetColor); // 计算颜色距离 double distance = Math.sqrt( Math.pow(r - pr, 2) + Math.pow(g - pg, 2) + Math.pow(b - pb, 2) ); if (distance < COLOR_TOLERANCE) { colorName = entry.getValue(); break; } } tvColorName.setText(colorName); tvDetectionStatus.setText(colorName.equals("未设定颜色") ? "识别区域" : "检测到: " + colorName); } @Override protected void onDestroy() { super.onDestroy(); if (cameraExecutor != null) { cameraExecutor.shutdown(); } } } 以上预设的颜色由于识别不够精准导致与需求不符,请改成预设颜色范围
最新发布
08-03
package com.example.demoapplication; // 定义包名 // 导入Android音频相关的类 import android.media.AudioTrack; import android.Manifest; import android.content.pm.PackageManager; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioRecord; import android.media.MediaRecorder; // 导入Android系统组件相关类 import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; // 导入语音合成相关类 import android.speech.tts.TextToSpeech; // 导入Android工具类 import android.util.Base64; import android.util.Log; // 导入Android UI组件 import android.widget.Button; import android.widget.Toast; // 导入Android兼容库组件 import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; // 导入JSON处理库 import org.json.JSONException; import org.json.JSONObject; // 导入IO流相关类 import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; // 导入网络通信相关类 import java.net.ServerSocket; import java.net.Socket; // 导入数据结构和并发工具 import java.util.LinkedList; import java.util.Locale; import java.util.Queue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * 主活动类,实现音频录制、播放、网络通信和TTS功能 */ public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener { private static final String TAG = "AudioRecorder"; // 日志标签 // 按钮成员变量 private Button startRecordButton, stopRecordButton; private Button playSoundButton, pauseSoundButton, stopSoundButton, resumeSoundButton, clearSoundsButton; // 音频录制对象 private AudioRecord audioRecord; // 音频采样率常量 private static final int SAMPLE_RATE = 16000; // 缓冲区大小常量 private static final int BUFFER_SIZE; // 静态代码块初始化缓冲区大小 static { // 获取最小缓冲区大小 int minBufferSize = AudioRecord.getMinBufferSize( SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT ); // 取较大值作为实际使用的缓冲区大小 BUFFER_SIZE = Math.max(minBufferSize, 4096); } // 调度执行器 private ScheduledExecutorService scheduler; // 录音状态标志 private AtomicBoolean isRecording = new AtomicBoolean(false); // 权限请求码 private static final int PERMISSION_REQUEST_CODE = 1; // 线程池服务 private final ExecutorService executorService = Executors.newCachedThreadPool(); // 服务器套接字 private ServerSocket serverSocket; // 服务器运行状态 private volatile boolean isServerRunning = true; // 客户端套接字 private volatile Socket clientSocket; // 套接字写入器 private volatile BufferedWriter socketWriter; // 文语转换引擎 private TextToSpeech ttsEngine; // TTS初始化状态 private boolean isTtsInitialized = false; // 播放队列相关变量 private final Queue<byte[]> playbackQueue = new LinkedList<>(); private final Queue<byte[]> pausedQueue = new LinkedList<>(); private final AtomicBoolean isPlaying = new AtomicBoolean(false); private final AtomicBoolean isPaused = new AtomicBoolean(false); private volatile boolean isPlaybackThreadActive = false; // ... existing code ... // 对象锁用于同步访问 private final Object audioTrackLock = new Object(); private final Object playbackQueueLock = new Object(); private final Object recordingQueueLock = new Object(); // 新增的成员变量 - 音频播放器 private AudioTrack audioTrack; // 新增的成员变量 // ... existing code ... // 录制音频数据队列 private final Queue<byte[]> recordingQueue = new LinkedList<>(); // 主线程消息处理器 private final Handler handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(@NonNull Message msg) { switch (msg.what) { case 0x11: // 客户端连接 Toast.makeText(MainActivity.this, "客户端已连接", Toast.LENGTH_SHORT).show(); break; case 0x12: // 开始录音 Toast.makeText(MainActivity.this, "开始录音", Toast.LENGTH_SHORT).show(); sendJsonPacket("startRecorder", null); playTts("开始录音"); break; case 0x14: // 停止录音 Toast.makeText(MainActivity.this, "停止录音", Toast.LENGTH_SHORT).show(); sendJsonPacket("stopRecorder", null); playTts("停止录音"); break; case 0x16: // 错误消息 Toast.makeText(MainActivity.this, "错误: " + msg.obj, Toast.LENGTH_LONG).show(); break; case 0x17: // 播放完成 Toast.makeText(MainActivity.this, "播放完成", Toast.LENGTH_SHORT).show(); isPlaying.set(false); isPlaybackThreadActive = false; updatePlayButtonsState(); break; case 0x18: // 添加到播放队列 Toast.makeText(MainActivity.this, "已添加到播放队列", Toast.LENGTH_SHORT).show(); break; case 0x19: // 更新播放按钮状态 updatePlayButtonsState(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 调用父类onCreate方法 setContentView(R.layout.activity_main); // 设置布局文件 // 初始化TTS引擎 ttsEngine = new TextToSpeech(this, this); // 初始化视图组件 initViews(); // 设置点击监听器 setupClickListeners(); // 检查权限 checkPermissions(); // 启动服务器(端口30000) startServer(30000); // 启动套接字监听 startSocketListener(); } // 初始化视图组件 private void initViews() { // 绑定按钮控件 startRecordButton = findViewById(R.id.startRecordButton); stopRecordButton = findViewById(R.id.stopRecordButton); playSoundButton = findViewById(R.id.playSoundButton); pauseSoundButton = findViewById(R.id.pauseSoundButton); stopSoundButton = findViewById(R.id.stopSoundButton); resumeSoundButton = findViewById(R.id.resumeSoundButton); clearSoundsButton = findViewById(R.id.clearSoundsButton); // 初始化按钮状态 stopRecordButton.setEnabled(false); pauseSoundButton.setEnabled(false); stopSoundButton.setEnabled(false); resumeSoundButton.setEnabled(false); } // 设置点击事件监听器 private void setupClickListeners() { // 录音控制 startRecordButton.setOnClickListener(v -> startRecording()); stopRecordButton.setOnClickListener(v -> stopRecording()); // 播放控制 playSoundButton.setOnClickListener(v -> playNextInQueue()); pauseSoundButton.setOnClickListener(v -> pausePlayback()); stopSoundButton.setOnClickListener(v -> stopPlayback()); resumeSoundButton.setOnClickListener(v -> resumePlayback()); clearSoundsButton.setOnClickListener(v -> { clearPlaybackQueue(); handler.sendEmptyMessage(0x19); }); } // ==================== 录音功能 ==================== // 开始录音 private void startRecording() { // 检查录音权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { sendErrorMessage("没有录音权限"); return; } // 如果已经在录音则先释放资源 if (isRecording.get()) { releaseAudioResources(); } try { // 创建AudioRecord对象 audioRecord = new AudioRecord( MediaRecorder.AudioSource.MIC, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE ); // 检查初始化状态 if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) { throw new IllegalStateException("AudioRecord 初始化失败"); } // 开始录音 audioRecord.startRecording(); isRecording.set(true); startRecordButton.setEnabled(false); stopRecordButton.setEnabled(true); updatePlayButtonsState(); // 关闭之前的调度器 if (scheduler != null && !scheduler.isShutdown()) { scheduler.shutdownNow(); } // 创建新的调度器 scheduler = Executors.newSingleThreadScheduledExecutor(); // 每100毫秒采集一次音频数据 scheduler.scheduleAtFixedRate(this::captureAudioData, 0, 100, TimeUnit.MILLISECONDS); handler.sendEmptyMessage(0x12); } catch (Exception e) { Log.e(TAG, "录音启动失败", e); sendErrorMessage("录音启动失败: " + e.getMessage()); releaseAudioResources(); } } // 停止录音 private void stopRecording() { if (!isRecording.get()) return; isRecording.set(false); releaseAudioResources(); stopRecordButton.setEnabled(false); startRecordButton.setEnabled(true); updatePlayButtonsState(); handler.sendEmptyMessage(0x14); } // 采集音频数据 private void captureAudioData() { if (!isRecording.get() || audioRecord == null) return; byte[] buffer = new byte[BUFFER_SIZE]; try { int bytesRead = audioRecord.read(buffer, 0, BUFFER_SIZE); if (bytesRead > 0) { synchronized (recordingQueueLock) { recordingQueue.offer(buffer.clone()); } String base64Data = Base64.encodeToString(buffer, Base64.DEFAULT); sendJsonPacket("recording", base64Data); } } catch (Exception e) { Log.e(TAG, "音频采集失败", e); } } // ==================== 录音功能结束 ==================== // ==================== 播放队列管理 ==================== // 将声音数据添加到播放队列 private void addSoundToQueue(byte[] soundData) { synchronized (playbackQueueLock) { playbackQueue.offer(soundData); } handler.sendEmptyMessage(0x18); // 如果没有在播放且没有激活的播放线程,则开始播放 if (!isPlaying.get() && !isPlaybackThreadActive) { handler.post(this::playNextInQueue); } } // 播放下一个队列中的音频 private void playNextInQueue() { if (isPlaybackThreadActive) { return; } isPlaybackThreadActive = true; new Thread(() -> { try { while (!playbackQueue.isEmpty() && !isPaused.get()) { byte[] soundData; synchronized (playbackQueueLock) { soundData = playbackQueue.poll(); } if (soundData != null) { playSoundDirectly(soundData); } } if (!isPaused.get()) { isPlaying.set(false); isPlaybackThreadActive = false; handler.sendEmptyMessage(0x17); } } catch (Exception e) { Log.e(TAG, "播放队列处理失败", e); sendErrorMessage("播放失败: " + e.getMessage()); } }).start(); } // 直接播放音频 private void playSoundDirectly(byte[] soundData) { if (soundData == null || soundData.length == 0) { return; } try { isPlaying.set(true); isPaused.set(false); synchronized (audioTrackLock) { int bufferSize = AudioTrack.getMinBufferSize( SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT ); if (audioTrack != null) { audioTrack.release(); } audioTrack = new AudioTrack( AudioManager.STREAM_MUSIC, SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM ); if (audioTrack.getState() != AudioTrack.STATE_INITIALIZED) { throw new IllegalStateException("AudioTrack 初始化失败"); } audioTrack.play(); ByteArrayInputStream inputStream = new ByteArrayInputStream(soundData); byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1 && !isPaused.get()) { audioTrack.write(buffer, 0, bytesRead); } audioTrack.stop(); audioTrack.release(); audioTrack = null; if (!isPaused.get()) { runOnUiThread(this::updatePlayButtonsState); } } } catch (Exception e) { Log.e(TAG, "音频播放失败", e); sendErrorMessage("播放失败: " + e.getMessage()); } } // 暂停播放 private void pausePlayback() { if (!isPlaying.get() || isPaused.get()) { return; } isPaused.set(true); synchronized (audioTrackLock) { if (audioTrack != null) { audioTrack.pause(); } } // 将当前播放的数据移到暂停队列 byte[] currentData = null; synchronized (playbackQueueLock) { if (!playbackQueue.isEmpty()) { currentData = playbackQueue.poll(); } } if (currentData != null) { synchronized (playbackQueueLock) { pausedQueue.offer(currentData); } } updatePlayButtonsState(); } // 恢复播放 private void resumePlayback() { if (!isPaused.get()) { return; } isPaused.set(false); // 将暂停的数据移回播放队列 byte[] pausedData = null; synchronized (playbackQueueLock) { if (!pausedQueue.isEmpty()) { pausedData = pausedQueue.poll(); } } if (pausedData != null) { synchronized (playbackQueueLock) { playbackQueue.offer(pausedData); } } synchronized (audioTrackLock) { if (audioTrack != null && audioTrack.getPlayState() == AudioTrack.PLAYSTATE_PAUSED) { audioTrack.play(); } } if (!isPlaybackThreadActive) { new Thread(() -> { isPlaybackThreadActive = true; try { while (!playbackQueue.isEmpty() && !isPaused.get()) { byte[] soundData; synchronized (playbackQueueLock) { soundData = playbackQueue.poll(); } if (soundData != null) { playSoundDirectly(soundData); } } if (!isPaused.get()) { isPlaying.set(false); isPlaybackThreadActive = false; handler.sendEmptyMessage(0x17); } } catch (Exception e) { Log.e(TAG, "恢复播放失败", e); sendErrorMessage("恢复播放失败: " + e.getMessage()); } }).start(); } updatePlayButtonsState(); } // 停止播放 private void stopPlayback() { if (!isPlaying.get() && !isPaused.get()) { return; } isPlaying.set(false); isPaused.set(false); synchronized (playbackQueueLock) { playbackQueue.clear(); if (!pausedQueue.isEmpty()) { pausedQueue.clear(); } } synchronized (audioTrackLock) { if (audioTrack != null) { try { audioTrack.stop(); audioTrack.release(); } catch (Exception e) { Log.e(TAG, "停止音频播放失败", e); } finally { audioTrack = null; } } } updatePlayButtonsState(); handler.sendEmptyMessage(0x19); } // 清空播放队列 private void clearPlaybackQueue() { synchronized (playbackQueueLock) { playbackQueue.clear(); pausedQueue.clear(); } } // ==================== 播放队列管理结束 ==================== // ==================== 辅助方法 ==================== // 更新播放按钮状态 private void updatePlayButtonsState() { runOnUiThread(() -> { boolean hasRecordings = !playbackQueue.isEmpty() || !pausedQueue.isEmpty(); boolean isPlayingState = isPlaying.get() && !isPaused.get(); boolean isPausedState = isPaused.get(); playSoundButton.setEnabled(hasRecordings && !isPlayingState); pauseSoundButton.setEnabled(isPlayingState); stopSoundButton.setEnabled(isPlaying.get() || isPausedState); resumeSoundButton.setEnabled(isPausedState); clearSoundsButton.setEnabled(hasRecordings); }); } // 播放文本转语音 private void playTts(String text) { if (isTtsInitialized) { ttsEngine.speak(text, TextToSpeech.QUEUE_FLUSH, null); } } // 释放音频资源 private void releaseAudioResources() { if (audioRecord != null) { try { if (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) { audioRecord.stop(); } audioRecord.release(); } catch (IllegalStateException e) { Log.e(TAG, "停止录音失败", e); } finally { audioRecord = null; } } if (scheduler != null) { try { scheduler.shutdownNow(); if (!scheduler.awaitTermination(500, TimeUnit.MILLISECONDS)) { Log.w(TAG, "录音线程池未正常关闭"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { scheduler = null; } } } // 发送JSON数据包 private void sendJsonPacket(String type, Object data) { if (clientSocket == null || clientSocket.isClosed() || socketWriter == null) { return; } try { JSONObject packet = new JSONObject(); packet.put("type", type); if (data != null) { packet.put("data", data); } synchronized (this) { if (socketWriter != null) { socketWriter.write(packet.toString()); socketWriter.write("\n\n"); socketWriter.flush(); } } } catch (Exception e) { Log.e(TAG, "发送数据包失败: " + type, e); } } // 发送错误消息 private void sendErrorMessage(String message) { handler.obtainMessage(0x16, message).sendToTarget(); } // 检查权限 private void checkPermissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSION_REQUEST_CODE ); } } // 启动服务器 private void startServer(int port) { executorService.execute(() -> { try { serverSocket = new ServerSocket(port); Log.i(TAG, "服务器启动: " + port); while (isServerRunning) { try { Socket socket = serverSocket.accept(); clientSocket = socket; synchronized (this) { socketWriter = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream(), "UTF-8") ); } handler.sendEmptyMessage(0x11); } catch (IOException e) { if (isServerRunning) Log.e(TAG, "接受连接失败", e); } } } catch (IOException e) { Log.e(TAG, "服务器启动失败", e); runOnUiThread(() -> Toast.makeText( this, "服务器启动失败: " + e.getMessage(), Toast.LENGTH_LONG ).show()); } finally { closeServerSocket(); } }); } // 启动套接字监听 private void startSocketListener() { executorService.execute(() -> { while (true) { if (clientSocket != null && !clientSocket.isClosed()) { try { BufferedReader reader = new BufferedReader( new InputStreamReader(clientSocket.getInputStream(), "UTF-8") ); StringBuilder packetBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { if (line.isEmpty()) { if (packetBuilder.length() > 0) { String packet = packetBuilder.toString(); Log.d(TAG, "收到数据包: " + packet); try { JSONObject command = new JSONObject(packet); String type = command.getString("type"); switch (type) { case "playSound": String base64Sound = command.optString("data"); if (base64Sound != null && !base64Sound.isEmpty()) { byte[] soundData = Base64.decode(base64Sound, Base64.DEFAULT); addSoundToQueue(soundData); handler.sendEmptyMessage(0x18); } break; case "pauseSound": pausePlayback(); break; case "stopSound": stopPlayback(); break; case "resumeSound": resumePlayback(); break; case "clearSounds": clearPlaybackQueue(); handler.sendEmptyMessage(0x19); break; } } catch (JSONException e) { Log.e(TAG, "JSON解析失败", e); } packetBuilder.setLength(0); } } else { packetBuilder.append(line); } } } catch (IOException e) { Log.e(TAG, "Socket读取失败", e); } } else { try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } }); } // 关闭服务器套接字 private void closeServerSocket() { try { if (serverSocket != null && !serverSocket.isClosed()) { serverSocket.close(); } } catch (IOException e) { Log.w(TAG, "关闭ServerSocket失败", e); } } // TTS初始化回调 @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = ttsEngine.setLanguage(Locale.CHINESE); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e(TAG, "TTS语言不支持中文"); } else { isTtsInitialized = true; } } } // 销毁活动时清理资源 @Override protected void onDestroy() { super.onDestroy(); isServerRunning = false; if (ttsEngine != null) { ttsEngine.stop(); ttsEngine.shutdown(); } closeServerSocket(); closeSocket(clientSocket); stopRecording(); executorService.shutdown(); try { if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) { executorService.shutdownNow(); } } catch (InterruptedException e) { executorService.shutdownNow(); Thread.currentThread().interrupt(); } releaseAudioResources(); } // 关闭套接字 private void closeSocket(Socket socket) { try { if (socket != null && !socket.isClosed()) { socket.close(); } } catch (IOException e) { Log.w(TAG, "关闭Socket失败", e); } if (socket == clientSocket) { clientSocket = null; synchronized (this) { socketWriter = null; } } } } 我需要修改当前代码常按开始录音就会录音,松开按钮就会结束录音,类似于微信那种功能包括修改xml文件
07-22
1. 服务器端 - ChatServer.java import java.io.*; import java.net.*; import java.util.*; public class ChatServer { private static final int PORT = 8080; private static Set<PrintWriter> clientWriters = new HashSet<>(); public static void main(String[] args) { System.out.println("聊天服务器启动中..."); try (ServerSocket serverSocket = new ServerSocket(PORT)) { System.out.println("服务器已启动,监听端口: " + PORT); while (true) { new ClientHandler(serverSocket.accept()).start(); } } catch (IOException e) { System.out.println("服务器异常: " + e.getMessage()); } } private static class ClientHandler extends Thread { private Socket socket; private PrintWriter out; private BufferedReader in; private String nickname; // 存储实际昵称 public ClientHandler(Socket socket) { this.socket = socket; } public void run() { try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); // 读取客户端发送的第一条消息作为昵称 nickname = in.readLine(); if (nickname == null || nickname.trim().isEmpty()) { nickname = "匿名用户"; } synchronized (clientWriters) { clientWriters.add(out); } // 使用实际昵称广播加入消息 System.out.println(nickname + " 加入了聊天室"); broadcastSystemMessage(nickname + " 加入了聊天室"); String message; while ((message = in.readLine()) != null) { System.out.println("收到消息: " + message); broadcastMessage(message, out); } } catch (IOException e) { System.out.println("客户端断开: " + e.getMessage()); } finally { try { socket.close(); } catch (IOException e) { // 忽略 } synchronized (clientWriters) { clientWriters.remove(out); } // 使用实际昵称广播退出消息 if (nickname != null) { System.out.println(nickname + " 离开了聊天室"); broadcastSystemMessage(nickname + " 离开了聊天室"); } } } private void broadcastMessage(String message, PrintWriter senderWriter) { synchronized (clientWriters) { for (PrintWriter writer : clientWriters) { if (writer != senderWriter) { writer.println(message); } } } } private void broadcastSystemMessage(String message) { long timestamp = System.currentTimeMillis(); String systemMessage = "系统|" + message + "|" + timestamp; synchronized (clientWriters) { for (PrintWriter writer : clientWriters) { writer.println(systemMessage); } } } } } 2.Android客户端AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapplication"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="骆树涛群聊" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.Light.NoActionBar"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ChatActivity" /> <activity android:name=".SettingsActivity" /> </application> </manifest> arrays.xml代码 <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="color_entries"> <item>黑色</item> <item>红色</item> <item>黄色</item> <item>蓝色</item> <item>绿色</item> </string-array> <string-array name="color_values"> <item>#FF000000</item> <item>#FFFF0000</item> <item>#FFFFFF00</item> <item>#FF0000FF</item> <item>#FF00FF00</item> </string-array> <string-array name="bg_entries"> <item>科技</item> <item>书籍</item> <item>简约</item> </string-array> <string-array name="bg_values"> <item>bg_books</item> <item>bg_nature</item> <item>bg_simple</item> </string-array> </resources> Srimg.xml代码 <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <EditTextPreference android:key="font_size" android:title="字号设置" android:summary="输入文字大小(单位:sp)" android:dialogTitle="设置字号" android:defaultValue="15" android:inputType="number"/> <ListPreference android:key="text_color" android:title="文字颜色" android:summary="选择文字显示颜色" android:dialogTitle="选择颜色" android:defaultValue="#FF000000" android:entries="@array/color_entries" android:entryValues="@array/color_values"/> <ListPreference android:key="bg" android:title="聊天背景" android:summary="选择聊天背景图片" android:dialogTitle="选择背景" android:entries="@array/bg_entries" android:entryValues="@array/bg_values" android:defaultValue="bg_tech"/> </PreferenceScreen> ChatMessage.java package com.example.myapplication; public class ChatMessage { private String nickname; private String message; private long timestamp; private boolean isSelf; public ChatMessage(String nickname, String message, long timestamp, boolean isSelf) { this.nickname = nickname; this.message = message; this.timestamp = timestamp; this.isSelf = isSelf; } public String getNickname() { return nickname; } public String getMessage() { return message; } public long getTimestamp() { return timestamp; } public boolean isSelf() { return isSelf; } } ChatAdapter.java package com.example.myapplication; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.RecyclerView; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.MessageViewHolder> { private List<ChatMessage> messages; private Context context; public ChatAdapter(List<ChatMessage> messages, Context context) { this.messages = messages; this.context = context; } @Override public int getItemViewType(int position) { return messages.get(position).isSelf() ? 1 : 0; } @NonNull @Override public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view; if (viewType == 1) { view = inflater.inflate(R.layout.message_item_self, parent, false); } else { view = inflater.inflate(R.layout.message_item, parent, false); } return new MessageViewHolder(view); } @Override public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) { ChatMessage message = messages.get(position); holder.messageText.setText(message.getMessage()); holder.nicknameText.setText(message.getNickname()); // 格式化时间 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault()); holder.timeText.setText(sdf.format(new Date(message.getTimestamp()))); // 应用设置 - 特别处理自己消息的颜色 applySettings(holder, message.isSelf()); } private void applySettings(MessageViewHolder holder, boolean isSelf) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // 设置字号 float fontSize = Float.parseFloat(prefs.getString("font_size", "15")); holder.messageText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize); holder.nicknameText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize - 2); holder.timeText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize - 4); // 设置文字颜色 - 自己消息使用特殊颜色 String colorValue; if (isSelf) { // 自己消息使用固定颜色,确保可读性 colorValue = "#FF000000"; // 黑色 } else { colorValue = prefs.getString("text_color", "#FF000000"); } holder.messageText.setTextColor(Color.parseColor(colorValue)); holder.nicknameText.setTextColor(Color.parseColor(colorValue)); holder.timeText.setTextColor(Color.parseColor(colorValue)); } @Override public int getItemCount() { return messages.size(); } static class MessageViewHolder extends RecyclerView.ViewHolder { TextView nicknameText, messageText, timeText; public MessageViewHolder(@NonNull View itemView) { super(itemView); nicknameText = itemView.findViewById(R.id.nickname); messageText = itemView.findViewById(R.id.message); timeText = itemView.findViewById(R.id.time); } } } MainActivity.java package com.example.myapplication; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.widget.Button; import android.widget.EditText; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private static final int SETTINGS_REQUEST = 1; private EditText nicknameEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); nicknameEditText = findViewById(R.id.nickname_edit_text); Button enterChatButton = findViewById(R.id.enter_chat_button); Button settingsButton = findViewById(R.id.settings_button); // 从SharedPreferences加载保存的昵称 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String savedNickname = prefs.getString("nickname", ""); nicknameEditText.setText(savedNickname); enterChatButton.setOnClickListener(v -> { // 保存昵称到SharedPreferences String nickname = nicknameEditText.getText().toString().trim(); if (nickname.isEmpty()) { nickname = "匿名用户"; } SharedPreferences.Editor editor = prefs.edit(); editor.putString("nickname", nickname); editor.apply(); // 启动聊天室 Intent intent = new Intent(MainActivity.this, ChatActivity.class); startActivity(intent); }); settingsButton.setOnClickListener(v -> startActivityForResult( new Intent(MainActivity.this, SettingsActivity.class), SETTINGS_REQUEST)); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SETTINGS_REQUEST && resultCode == SettingsActivity.RESULT_SETTINGS_CHANGED) { // 设置已更改,更新主界面背景 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String bgKey = prefs.getString("bg", "bg_tech"); int bgResId = getResources().getIdentifier(bgKey, "drawable", getPackageName()); if (bgResId != 0) { findViewById(android.R.id.content).setBackgroundResource(bgResId); } } } } SettingsActivity.java package com.example.myapplication; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; public class SettingsActivity extends AppCompatActivity { public static final int RESULT_SETTINGS_CHANGED = 1001; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); getSupportFragmentManager() .beginTransaction() .replace(R.id.settings_container, new SettingsFragment()) .commit(); } } SettingsFragment.java  package com.example.myapplication; import android.content.SharedPreferences; import android.os.Bundle; import androidx.preference.PreferenceFragmentCompat; public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.sring, rootKey); } @Override public void onResume() { super.onResume(); getPreferenceManager().getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); getPreferenceManager().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // 设置变更时通知ChatActivity刷新 if (getActivity() != null) { getActivity().setResult(SettingsActivity.RESULT_SETTINGS_CHANGED); } } } ChatActivity.java  package com.example.myapplication; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.io.*; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class ChatActivity extends AppCompatActivity { private static final String SERVER_IP = "192.168.199.1"; // 模拟器访问本机 private static final int SERVER_PORT = 8080; private RecyclerView chatRecyclerView; private EditText messageEditText; private Button sendButton; private ChatAdapter adapter; private List<ChatMessage> messages = new ArrayList<>(); private PrintWriter out; private BufferedReader in; private Socket socket; private String nickname; private SharedPreferences prefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); // 从SharedPreferences获取昵称 prefs = PreferenceManager.getDefaultSharedPreferences(this); nickname = prefs.getString("nickname", "匿名用户"); setupUI(); loadChatHistory(); connectToServer(); } @Override protected void onResume() { super.onResume(); // 重新应用设置(从设置页面返回时) applyBackgroundSettings(); if (adapter != null) { adapter.notifyDataSetChanged(); // 刷新消息显示 } } private void setupUI() { chatRecyclerView = findViewById(R.id.chat_recycler_view); messageEditText = findViewById(R.id.message_edit_text); sendButton = findViewById(R.id.send_button); adapter = new ChatAdapter(messages, this); chatRecyclerView.setAdapter(adapter); chatRecyclerView.setLayoutManager(new LinearLayoutManager(this)); applyBackgroundSettings(); // 初始应用背景设置 sendButton.setOnClickListener(v -> sendMessage()); } private void applyBackgroundSettings() { String bgKey = prefs.getString("bg", "bg_tech"); int bgResId = getResources().getIdentifier(bgKey, "drawable", getPackageName()); if (bgResId != 0) { chatRecyclerView.setBackgroundResource(bgResId); } } private void loadChatHistory() { File file = new File(getExternalFilesDir(null), "luoshutao.txt"); if (file.exists()) { try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line; while ((line = reader.readLine()) != null) { String[] parts = line.split("\\|"); if (parts.length == 4) { boolean isSelf = Boolean.parseBoolean(parts[3]); messages.add(new ChatMessage(parts[0], parts[1], Long.parseLong(parts[2]), isSelf)); } } adapter.notifyDataSetChanged(); chatRecyclerView.scrollToPosition(messages.size() - 1); } catch (IOException e) { e.printStackTrace(); } } } private void saveChatMessage(ChatMessage message) { File file = new File(getExternalFilesDir(null), "luoshutao.txt"); try (FileWriter writer = new FileWriter(file, true)) { writer.write(String.format("%s|%s|%d|%b\n", message.getNickname(), message.getMessage(), message.getTimestamp(), message.isSelf())); } catch (IOException e) { e.printStackTrace(); } } private void connectToServer() { new Thread(() -> { try { socket = new Socket(SERVER_IP, SERVER_PORT); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.println(nickname); // 监听服务器消息 String serverMessage; while ((serverMessage = in.readLine()) != null) { if (isSystemJoinLeaveMessage(serverMessage)) { continue; // 跳过不显示 } // 解析服务器消息:格式为 "昵称|消息|时间戳" String[] parts = serverMessage.split("\\|", 3); if (parts.length == 3) { final ChatMessage message = new ChatMessage( parts[0], parts[1], Long.parseLong(parts[2]), false ); runOnUiThread(() -> { messages.add(message); adapter.notifyItemInserted(messages.size() - 1); chatRecyclerView.scrollToPosition(messages.size() - 1); saveChatMessage(message); }); } } } catch (IOException e) { runOnUiThread(() -> Toast.makeText(ChatActivity.this, "服务器连接失败: " + e.getMessage(), Toast.LENGTH_LONG).show()); } }).start(); } private boolean isSystemJoinLeaveMessage(String message) { return message.contains("加入了聊天室") || message.contains("离开了聊天室"); } private void sendMessage() { String messageText = messageEditText.getText().toString().trim(); if (!messageText.isEmpty()) { long timestamp = System.currentTimeMillis(); final ChatMessage message = new ChatMessage(nickname, messageText, timestamp, true); // 添加到UI runOnUiThread(() -> { messages.add(message); adapter.notifyItemInserted(messages.size() - 1); chatRecyclerView.scrollToPosition(messages.size() - 1); saveChatMessage(message); }); // 发送到服务器 new Thread(() -> { if (out != null) { out.println(nickname + "|" + messageText + "|" + timestamp); } }).start(); messageEditText.setText(""); } } @Override protected void onDestroy() { super.onDestroy(); try { if (socket != null) socket.close(); if (out != null) out.close(); if (in != null) in.close(); } catch (IOException e) { e.printStackTrace(); } } } activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" android:padding="16dp" android:background="@drawable/bg_tech"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="骆树涛聊天室" android:textSize="40sp" android:layout_gravity="center" android:layout_marginBottom="16dp" android:textStyle="bold" android:textColor="#2196F3"/> <!-- 昵称设置区域 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_vertical" android:layout_marginBottom="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="昵称:" android:textSize="25sp" android:layout_marginEnd="8dp"/> <EditText android:id="@+id/nickname_edit_text" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="请输入昵称" android:textSize="25sp" android:maxLines="1"/> </LinearLayout> <Button android:id="@+id/enter_chat_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="进入聊天室" android:layout_marginBottom="16dp"/> <Button android:id="@+id/settings_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="设置"/> </LinearLayout> activity_chat.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/chat_recycler_view" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:scrollbars="vertical"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="8dp"> <EditText android:id="@+id/message_edit_text" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="输入消息" android:inputType="textMultiLine" android:maxLines="3"/> <Button android:id="@+id/send_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送"/> </LinearLayout> </LinearLayout> activity_settings.xml  <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/settings_container" android:layout_width="match_parent" android:layout_height="match_parent" /> message_item.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="8dp" android:layout_marginTop="4dp" android:layout_marginEnd="60dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_vertical"> <TextView android:id="@+id/nickname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12sp"/> <TextView android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10sp" android:layout_marginStart="8dp"/> </LinearLayout> <TextView android:id="@+id/message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bubble_other" android:padding="8dp"/> </LinearLayout> message_item_self.xml  <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="8dp" android:layout_marginTop="4dp" android:layout_marginStart="60dp" android:gravity="end"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_vertical"> <TextView android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10sp" android:layout_marginEnd="8dp"/> <TextView android:id="@+id/nickname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12sp"/> </LinearLayout> <TextView android:id="@+id/message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bg_books" android:padding="8dp"/> </LinearLayout>
06-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值