我有一个主要的类来管理我的应用程序的ui和其他东西。
还有另一个名为BluetoothConnection的类来管理bt连接。
我是java的新手,我需要了解的是如何使用这个外部类!我知道这是一个非常简单的问题:)
我正在使用
初始化主要的第二节课private BluetoothConnection btConnection;
然后在主要类onCreat方法中我正在做:
btConnection.run();
是吗?我的应用程序崩溃,但可能是出于其他原因。
这是第二类的代码
public class BluetoothConnection extends Thread{
public BluetoothSocket mmSocket = null;
public BluetoothAdapter mAdapter;
private InputStream mmInStream = null;
private OutputStream mmOutStream = null;
byte[] buffer;
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
public BluetoothConnection(BluetoothDevice device) {
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
//now make the socket connection in separate thread to avoid FC
Thread connectionThread = new Thread(new Runnable() {
@Override
public void run() {
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
//connection to device failed so close the socket
try {
mmSocket.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
});
connectionThread.start();
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
buffer = new byte[1024];
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
// Keep listening to the InputStream while connected
while (true) {
try {
//read the data from socket stream
mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
} catch (IOException e) {
//an exception here marks connection loss
//send message to UI Activity
break;
}
}
}
public void write(byte[] buffer) {
try {
//write the data to socket stream
mmOutStream.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}