我写了下面的代码。每次我运行它时,应用程序都会停止。 你有什么想法可以帮我吗?
如果我不启动工作线程,代码就可以了。 我的问题是:
我可以从UI线程上的onCreate
函数启动工作线程吗?
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private Bluetooth mBluetooth = null;
private Gauge mGauge;
private Obd2 mObd2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v7.widget.Toolbar myToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
mGauge = findViewById(R.id.gauge1);
mGauge.setValue(120);
mBluetooth = new Bluetooth();
try {
mBluetooth.connect();
} catch (IOException e) {
}
mObd2 = new Obd2(mBluetooth);
mObd2.command(obd2CommandEnum.RESET);
runRPMThread();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.menu, menu);
return true;
}
private void runRPMThread() {
new Thread() {
public void run() {
while (true) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
mGauge.setValue(mObd2.rpm());
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
答案 0 :(得分:0)
只是调试到问题所在... mObd2.rpm()函数中有一个空指针。我需要通过蓝牙与汽车连接运行该应用程序。没有那个,我有一个空指针...