我一直在创建一个蓝牙应用程序,一切正常,从打开和关闭,搜索设备,可见设备,打开服务器,设置客户端。一切正常,设备可以配对。但是当我想使用Input / OutputStream执行数据传输时,崩溃就开始了。
代码没有错误,但在执行connectedThread功能时崩溃了。这是代码
private class ConnectedThread extends Thread {
private final BluetoothSocket mySocket;
private final InputStream myInStream;
private final OutputStream myOutStream;
public ConnectedThread(BluetoothSocket socket) {
mySocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
myInStream = tmpIn; <-------MainActivity.Java:623
myOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;
while (true) {
try {
bytes += myInStream.read(buffer, bytes, buffer.length - bytes);
for (int i = begin; i < bytes; i++) {
if (buffer[i] == "#".getBytes()[0]) {
myHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
begin = i + 1;
if (i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
break;
}
}
}
public void write(byte[] bytes) {
try {
myOutStream.write(bytes);
} catch (IOException e) {
}
}
public void cancel() {
try {
mySocket.close();
} catch (IOException e) {
}
}
Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int) msg.arg1;
int end = (int) msg.arg2;
switch (msg.what) {
case 1:
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
break;
}
}
};
}
connectedThread从这里被激活
transferBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConnectedThread t = new ConnectedThread(socket);<------MainActivity.Java:192
t.start();
});
Logcat显示此
07-14 02:53:04.937 16812-16812 / com.example.heszrave.bluetoothremote E / AndroidRuntime:FATAL EXCEPTION:main 显示java.lang.NullPointerException 在com.example.heszrave.bluetoothremote.MainActivity $ ConnectedThread。(MainActivity.java:623) 在com.example.heszrave.bluetoothremote.MainActivity $ 6.onClick(MainActivity.java:192)
当我点击MainActivity.Java:623时,它指向myInStream = tmpIn;
的MainActivity.Java:192它指向了触发事件ConnectedThread t = new ConnectedThread(socket);