Java Android:蓝牙-如何读取传入数据
我已成功配对并连接蓝牙设备。我现在感兴趣的是接收在2之间传输的所有数据,看看是什么 我正在从套接字获取输入流并尝试读取它。我返回这个并记录它 从我读到的内容中,我知道的唯一方法就是使用字节缓冲区进行读取,以返回一个int。但是,我应该有大量的数据通过。如何连续读取正在传输的数据,并将其格式化为字节而不是整数 谢谢 完整代码如下:Java Android:蓝牙-如何读取传入数据,java,android,multithreading,bluetooth,stream,Java,Android,Multithreading,Bluetooth,Stream,我已成功配对并连接蓝牙设备。我现在感兴趣的是接收在2之间传输的所有数据,看看是什么 我正在从套接字获取输入流并尝试读取它。我返回这个并记录它 从我读到的内容中,我知道的唯一方法就是使用字节缓冲区进行读取,以返回一个int。但是,我应该有大量的数据通过。如何连续读取正在传输的数据,并将其格式化为字节而不是整数 谢谢 完整代码如下: public class ConnectThread { private BluetoothSocketWrapper bluetoothSocket;
public class ConnectThread {
private BluetoothSocketWrapper bluetoothSocket;
private BluetoothDevice device;
private boolean secure;
private BluetoothAdapter adapter;
private List<UUID> uuidCandidates;
private int candidate;
/**
* @param device the device
* @param secure if connection should be done via a secure socket
* @param adapter the Android BT adapter
* @param uuidCandidates a list of UUIDs. if null or empty, the Serial PP id is used
*/
public ConnectThread(BluetoothDevice device, boolean secure, BluetoothAdapter adapter,
List<UUID> uuidCandidates) {
this.device = device;
this.secure = secure;
this.adapter = adapter;
this.uuidCandidates = uuidCandidates;
if (this.uuidCandidates == null || this.uuidCandidates.isEmpty()) {
this.uuidCandidates = new ArrayList<UUID>();
this.uuidCandidates.add(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
}
}
public BluetoothSocketWrapper connect() throws IOException {
boolean success = false;
while (selectSocket()) {
adapter.cancelDiscovery();
try {
bluetoothSocket.connect();
success = true;
break;
} catch (IOException e) {
//try the fallback
try {
bluetoothSocket = new FallbackBluetoothSocket(bluetoothSocket.getUnderlyingSocket());
Thread.sleep(500);
bluetoothSocket.connect();
success = true;
break;
} catch (FallbackException e1) {
Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e);
} catch (InterruptedException e1) {
Log.w("BT", e1.getMessage(), e1);
} catch (IOException e1) {
Log.w("BT", "Fallback failed. Cancelling.", e1);
}
}
}
if (!success) {
throw new IOException("Could not connect to device: "+ device.getAddress());
}
receiveData(bluetoothSocket);
return bluetoothSocket;
}
private boolean selectSocket() throws IOException {
if (candidate >= uuidCandidates.size()) {
return false;
}
BluetoothSocket tmp;
UUID uuid = uuidCandidates.get(candidate++);
Log.i("BT", "Attempting to connect to Protocol: "+ uuid);
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(uuid);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(uuid);
}
bluetoothSocket = new NativeBluetoothSocket(tmp);
return true;
}
public static interface BluetoothSocketWrapper {
InputStream getInputStream() throws IOException;
OutputStream getOutputStream() throws IOException;
String getRemoteDeviceName();
void connect() throws IOException;
String getRemoteDeviceAddress();
void close() throws IOException;
BluetoothSocket getUnderlyingSocket();
}
public static class NativeBluetoothSocket implements BluetoothSocketWrapper {
private BluetoothSocket socket;
public NativeBluetoothSocket(BluetoothSocket tmp) {
this.socket = tmp;
}
@Override
public InputStream getInputStream() throws IOException {
return socket.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return socket.getOutputStream();
}
@Override
public String getRemoteDeviceName() {
return socket.getRemoteDevice().getName();
}
@Override
public void connect() throws IOException {
socket.connect();
}
@Override
public String getRemoteDeviceAddress() {
return socket.getRemoteDevice().getAddress();
}
@Override
public void close() throws IOException {
socket.close();
}
@Override
public BluetoothSocket getUnderlyingSocket() {
return socket;
}
}
public class FallbackBluetoothSocket extends NativeBluetoothSocket {
private BluetoothSocket fallbackSocket;
public FallbackBluetoothSocket(BluetoothSocket tmp) throws FallbackException {
super(tmp);
try
{
Class<?> clazz = tmp.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[] {Integer.valueOf(1)};
fallbackSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
}
catch (Exception e)
{
throw new FallbackException(e);
}
}
@Override
public InputStream getInputStream() throws IOException {
return fallbackSocket.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return fallbackSocket.getOutputStream();
}
@Override
public void connect() throws IOException {
fallbackSocket.connect();
}
@Override
public void close() throws IOException {
fallbackSocket.close();
}
}
public static class FallbackException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public FallbackException(Exception e) {
super(e);
}
}
public void sendData(BluetoothSocketWrapper socket, int data) throws IOException{
ByteArrayOutputStream output = new ByteArrayOutputStream(4);
output.write(data);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(output.toByteArray());
}
public int receiveData(BluetoothSocketWrapper socket) throws IOException{
byte[] buffer = new byte[256];
ByteArrayInputStream input = new ByteArrayInputStream(buffer);
InputStream inputStream = socket.getInputStream();
inputStream.read(buffer);
return input.read();
}
}
公共类连接线程{
私人蓝牙插座Rapper蓝牙插座;
私人蓝牙设备;
私有布尔安全;
私人蓝牙适配器;
私人候选人名单;
私人int候选人;
/**
*@param-device设备
*@param secure if应通过安全套接字进行连接
*@param适配器Android BT适配器
*@param UUID是UUID的列表。如果为null或空,则使用串行PP id
*/
公共连接线程(蓝牙设备、布尔安全、蓝牙适配器、,
(候选人名单){
这个装置=装置;
这是安全的;
this.adapter=适配器;
this.uuidCandidates=uuidCandidates;
if(this.uuidCandidates==null | | this.uuidCandidates.isEmpty()){
this.uuidCandidates=新的ArrayList();
这个.uuidCandidates.add(UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
}
}
公共BluetoothSocketTrapper connect()引发IOException{
布尔成功=假;
while(selectSocket()){
adapter.cancelDiscovery();
试一试{
bluetoothSocket.connect();
成功=真实;
打破
}捕获(IOE异常){
//试着退一步
试一试{
bluetoothSocket=新的FallbackBluetoothSocket(bluetoothSocket.getUnderlineingSocket());
睡眠(500);
bluetoothSocket.connect();
成功=真实;
打破
}捕获(回退异常e1){
Log.w(“BT”,“无法初始化FallbackBluetoothSocket类。”,e);
}捕捉(中断异常e1){
Log.w(“BT”,e1.getMessage(),e1);
}捕获(IOE1异常){
Log.w(“BT”,“回退失败。取消”,e1);
}
}
}
如果(!成功){
抛出新IOException(“无法连接到设备:+device.getAddress());
}
接收数据(蓝牙插座);
返回蓝牙插座;
}
私有布尔selectSocket()引发IOException{
如果(候选对象>=uuidCandidates.size()){
返回false;
}
蓝牙插座;
UUID-UUID=uuidCandidates.get(candidate++);
Log.i(“BT”,“试图连接到协议:+uuid”);
如果(安全){
tmp=设备.createrFComSocketToServiceRecord(uuid);
}否则{
tmp=设备.createInsurerCommsocketToServiceRecord(uuid);
}
bluetoothSocket=新的本地bluetoothSocket(tmp);
返回true;
}
公共静态接口BluetoothSocketRapper{
InputStream getInputStream()抛出IOException;
OutputStream getOutputStream()抛出IOException;
字符串getRemoteDeviceName();
void connect()抛出IOException;
字符串getRemoteDeviceAddress();
void close()抛出IOException;
BluetoothSocket getUnderlyingSocket();
}
公共静态类NativeBluetoothSocket实现BluetoothSocketTrapper{
私人蓝牙插座;
公共NativeBluetoothSocket(BluetoothSocket tmp){
this.socket=tmp;
}
@凌驾
公共InputStream getInputStream()引发IOException{
返回socket.getInputStream();
}
@凌驾
public OutputStream getOutputStream()引发IOException{
返回socket.getOutputStream();
}
@凌驾
公共字符串getRemoteDeviceName(){
返回socket.getRemoteDevice().getName();
}
@凌驾
public void connect()引发IOException{
socket.connect();
}
@凌驾
公共字符串getRemoteDeviceAddress(){
返回socket.getRemoteDevice().getAddress();
}
@凌驾
public void close()引发IOException{
socket.close();
}
@凌驾
公共BluetoothSocket GetUnderlineingSocket(){
返回插座;
}
}
公共类FallbackBluetoothSocket扩展了NativeBluetoothSocket{
私人蓝牙插座后备插座;
公共FallbackBluetoothSocket(BluetoothSocket tmp)引发FallbackException{
超级(tmp);
尝试
{
类clazz=tmp.getRemoteDevice().getClass();
类[]paramTypes=新类[]{Integer.TYPE};
方法m=clazz.getMethod(“createRfcommSocket”,paramTypes);
Object[]params=新对象[]{Integer.valueOf(1)};
fallbackSocket=(BluetoothSocket)m.invoke(tmp.getRemoteDevice(),params);
}
捕获(例外e)
{
抛出新的回退异常(e);
}
}
@凌驾
公共InputStream getInputStream()引发IOException{
返回fallbackSocket.getInputStream();
}
@凌驾
public OutputStream getOutputStream()引发IOException{
返回fallbackSocket.getOutputStream();
}
@
String text = "My message";
socketOutputStream.write(text.getBytes());
int length = socketInputStream.read(buffer);
String text = new String(buffer, 0, length);
int length;
while ((length = largeDataInputStream.read(buffer)) != -1) {
socketOutputStream.write(buffer, 0, length);
}
int length;
//socketInputStream never returns -1 unless connection is broken
while ((length = socketInputStream.read(buffer)) != -1) {
largeDataOutputStream.write(buffer, 0, length);
if (progress >= dataSize) {
break; //Break loop if progress reaches the limit
}
}
public void receiveData(BluetoothSocketWrapper socket) throws IOException{
InputStream socketInputStream = socket.getInputStream();
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = socketInputStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
Log.i("logging", readMessage + "");
} catch (IOException e) {
break;
}
}
}