我正在使用蓝牙开发Android应用。我想让write和read在两个独立的线程中运行。
写线程
class Write extends Thread {
public void run(){
while(Bluetooth.threadStateWrite){
if(LLTestAppActivity.DEBUG){
Log.d("BLUETOOTH_WRITE", "Write Thread Running!");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
阅读主题
class Read extends Thread {
public void run(){
while(Bluetooth.threadStateRead){
if(LLTestAppActivity.DEBUG){
Log.d("BLUETOOTH_READ", "Read Thread Running!");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
我从以下蓝牙类中调用这两个主题:
public class Bluetooth {
Write write;
Read read;
//Constructor
public Bluetooth() {
write.start();
read.start();
}
Write和Read类在Bluetooth类中。
因此,当我尝试实例化蓝牙类时,我在构造函数中获得了NullPointer异常。任何人都可以指导我如何做到这一点?提前谢谢。
答案 0 :(得分:2)
在调用write
方法之前,您需要使用类构造函数初始化read
和start
:
public Bluetooth() {
write=new Write(); //create Write class Object
write.start();
read=new Read(); //create Read class Object
read.start();
}