【发布时间】:2022-09-27 21:31:07
【问题描述】:
我一直在尝试使我的蓝牙连接线程能够通过小吃店向用户发送消息,但它们从未出现在屏幕上。
在主要方法中:
//listener for connect button
try {
Button btn_connect = findViewById(R.id.btn_connect);
btn_connect.setOnClickListener(view -> {
if(bluetoothService.isStarted()){
snackbarMsg(findViewById(R.id.btn_connect), \"Bluetooth connection already established\");
} else{
new Thread(() -> {
try {
Log.i(TAG, \"New thread started\");
bluetoothService.run(MainActivity.this);
Log.i(TAG,\"Bluetooth service started\");
snackbarMsg(findViewById(R.id.btn_connect), \"Bluetooth service started\");
} catch (Exception e) {
Log.e(TAG, \"Bluetooth service failed\", e);
}
}).start();
}
});
} catch (Exception exception){
Log.e(TAG, \"Bluetooth service failed\");
}
在蓝牙服务类中:
public void snackbarMsg (View view, String msg){
try {
Snackbar snackbar = Snackbar.make(view, msg, BaseTransientBottomBar.LENGTH_SHORT);
snackbar.show();
} catch (Exception exception){
Log.e(TAG, \"Could not show snackbar\", exception);
}
}
我使用该方法发送的视图总是在主屏幕上,例如使用 \"snackbarMsg(findViewById(R.id.button_send),\"Failed to find bluetooth server\");\" button_send 在屏幕上我想显示小吃栏的位置。
我尝试使用 runnables 并扩展线程等等。但是由于我已经在 bluetoothservice 类上进行了扩展但不起作用,并且 runnable 被证明很麻烦,因为我需要在启动 run 方法时发送上下文,并且该上下文似乎无法在较早的状态下发送,这意味着我无法在创建时发送该信息和程序开头的蓝牙服务对象。
其次:我不确定我什至需要第二个线程,因为我的蓝牙连接只是发送数据,而不是接收,我只是在做无用的工作吗?
标签: java android multithreading android-snackbar