Для обработки данных с Bluetooth-джойстика потребуется доступ к потоку ввода, чтобы читать данные, которые передаются с устройства. В приведённом ниже коде добавлена базовая реализация для подключения, чтения и обработки данных от джойстика. Основываясь на концепции, вы сможете расширить обработку под ваши нужды.
Обновленный код с обработкой данных от джойстика
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private TextureView textureView;
private CameraDevice cameraDevice;
private CameraCaptureSession cameraCaptureSession;
private static final int CAMERA_PERMISSION_REQUEST_CODE = 200;
private static final int BLUETOOTH_PERMISSION_REQUEST_CODE = 100;
private BluetoothAdapter bluetoothAdapter;
private BluetoothSocket bluetoothSocket;
private static final UUID MY_UUID = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private Thread bluetoothThread;
private InputStream inputStream;
private Handler handler = new Handler(Looper.getMainLooper());
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textureView = findViewById(R.id.textureView);
textureView.setSurfaceTextureListener(textureListener);
// Initialize Bluetooth
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_SHORT).show();
} else if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, BLUETOOTH_PERMISSION_REQUEST_CODE);
} else {
connectToBluetoothDevice();
}
}
private void connectToBluetoothDevice() {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// Replace "YOUR_DEVICE_NAME" with the actual name of your device
if (device.getName().equals("YOUR_DEVICE_NAME")) {
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
bluetoothSocket.connect();
inputStream = bluetoothSocket.getInputStream();
initiateBluetoothListener();
Toast.makeText(this, "Connected to Bluetooth device", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.e("Bluetooth", "Connection failed", e);
}
break;
}
}
} else {
Toast.makeText(this, "No paired Bluetooth devices found", Toast.LENGTH_SHORT).show();
}
}
// Start a separate thread to listen to Bluetooth data
private void initiateBluetoothListener() {
bluetoothThread = new Thread(new Runnable() {
@Override
public void run() {
byte[] buffer = new byte[1024]; // Buffer store for the stream
int bytes; // Bytes returned from read()
while (true) {
try {
// Read from the InputStream
if ((bytes = inputStream.read(buffer)) != -1) {
String data = new String(buffer, 0, bytes);
processJoystickData(data);
}
} catch (IOException e) {
break;
}
}
}
});
bluetoothThread.start();
}
// Process data received from joystick
private void processJoystickData(String data) {
handler.post(() -> {
// Implement your logic here
Log.d("JoystickData", "Received Data: " + data);
// Example: Toast the data received from joystick
Toast.makeText(MainActivity.this, "Joystick Data: " + data, Toast.LENGTH_SHORT).show();
});
}
TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
return;
}
openCamera();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
drawBitmapOnCanvas();
}
};
private void openCamera() {
CameraManager cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraManager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice camera) {
cameraDevice = camera;
startCameraPreview();
}
@Override
public void onDisconnected(@NonNull CameraDevice camera) {
cameraDevice.close();
}
@Override
public void onError(@NonNull CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
Toast.makeText(MainActivity.this, "Camera error: " + error, Toast.LENGTH_SHORT).show();
}
};
private void startCameraPreview() {
try {
SurfaceTexture surfaceTexture = textureView.getSurfaceTexture();
surfaceTexture.setDefaultBufferSize(textureView.getWidth(), textureView.getHeight());
Surface surface = new Surface(surfaceTexture);
final CaptureRequest.Builder builder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
builder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
cameraCaptureSession = session;
builder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO);
try {
cameraCaptureSession.setRepeatingRequest(builder.build(), captureCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
Toast.makeText(MainActivity.this, "Failed to configure camera", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private final CameraCaptureSession.CaptureCallback captureCallback = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
drawBitmapOnCanvas();
}
};
private void drawBitmapOnCanvas() {
Bitmap bitmap = textureView.getBitmap();
if (bitmap == null) return;
Canvas canvas = textureView.lockCanvas();
if (canvas != null) {
int bitmapWidth = bitmap.getWidth() / 2;
int bitmapHeight = bitmap.getHeight();
Bitmap leftBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight);
Bitmap rightBitmap = Bitmap.createBitmap(bitmap, bitmapWidth, 0, bitmapWidth, bitmapHeight);
canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR); // Clear
canvas.drawBitmap(leftBitmap, 0, 0, null);
canvas.drawBitmap(rightBitmap, bitmapWidth, 0, null);
textureView.unlockCanvasAndPost(canvas);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
Toast.makeText(this, "Camera permission required", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onResume() {
super.onResume();
if (textureView.isAvailable()) {
openCamera();
} else {
textureView.setSurfaceTextureListener(textureListener);
}
}
@Override
protected void onPause() {
// Close camera and Bluetooth resources
if (cameraDevice != null) {
cameraDevice.close();
cameraDevice = null;
}
if (bluetoothSocket != null) {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bluetoothThread != null) {
bluetoothThread.interrupt();
bluetoothThread = null;
}
super.onPause();
}
}
Объяснение изменений:
- Bluetooth Listening: Запущен поток
bluetoothThread для ожидания данных с Bluetooth-джойстика, использующего входной поток inputStream.
- Данные джойстика: Метод
processJoystickData обрабатывает данные, полученные от джойстика. Вы можете изменить его, чтобы реализовать своё поведение на основе полученных входных данных.
- Обработка данных: Включает вывод в лог и возможность отображать данные через Toast (как пример).
Для корректной работы приложение должно быть дополнительно отлажено и протестировано с конкретным Bluetooth-джойстиком, так как разный джойстики могут отдавать разные форматы данных. Также стоит рассмотреть обработку ошибок и закрытие ресурсов при завершении работы приложения.