[英]Android java - Trying to show snackbar in new thread
我一直在嘗試使我的藍牙連接線程能夠通過小吃店向用戶發送消息,但它們從未出現在屏幕上。
在主要方法中:
//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");
}
在藍牙服務 class 中:
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),"無法找到藍牙服務器");” button_send 在屏幕上我想顯示小吃欄的位置。
我嘗試使用 runnables 並擴展線程等等。 但是由於我已經在 bluetoothservice class 上進行了擴展,但它不起作用,並且 runnable 被證明很麻煩,因為我需要在啟動運行方法時發送上下文,並且該上下文似乎無法在較早的 state 發送,這意味着我在創建時無法發送該信息和 object 來自藍牙服務在程序的開頭。
其次:我不確定我什至需要第二個線程,因為我的藍牙連接只是發送數據,而不是接收,我只是在做無用的工作嗎?
您需要在 UI/主線程上運行它。
使用runOnUiThread(action: Runnable)
runOnUiThread(() -> snackbarMsg(view, "insert message"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.