[英]Android send data from Thread in separate java class to UI thread
我的MainActivity,ConnectThread和ConnectedThread位於單獨的類中。
我正在從ConnectedThread中的Bluetoothmodule監聽許多數據。
我的主線程中有如下的Broadcastreciever:
final BroadcastReceiver bReciever = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String message = intent.getStringExtra("data");
if(BluetoothDevice.ACTION_FOUND.equals(action)){ // Bluetooth discovery result found
BTArrayAdapter_found_filter.clear(); //Remove Duplicates
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter_found.add(device.getName()+"\n"+device.getAddress());
BTArrayAdapter_found.notifyDataSetChanged();
for(int i = 0;i< BTArrayAdapter_found.getCount();i++){ // Iterate original Arrayadapter for filtering
String filter = "RCD";
if(BTArrayAdapter_found.getItem(i).toString().toLowerCase().contains(filter.toLowerCase())){
BTArrayAdapter_found_filter.add(BTArrayAdapter_found.getItem(i));
BTArrayAdapter_found_filter.notifyDataSetChanged();
}
}
}
if(message!=null)
textview_terminal.setText(message);
}
};
我會聽消息並將其傳遞給textview。 另一個只是藍牙部分,此處不相關。
我在ConnectedThread中有這樣的意圖:
public void sendData(){
Intent sendDataIntent = new Intent("SendData_EVENT");
sendDataIntent.putExtra("data",passData);
LocalBroadcastManager.getInstance().sendBroadcast(sendDataIntent);
}
但是由於該線程與Activity沒有連接,所以Broadcastmanagers getInstance不起作用。
我正在嘗試使用以下示例: LINK
我看了很多示例,但我認為處理程序不是我的最佳方法。
如何成功從后台線程發送數據?
通過將發送getApplicationContext()發送給ConnectedThread構造函數並將其傳遞給getInstance(context)來解決
通過將發送getApplicationContext()發送給ConnectedThread構造函數並將其傳遞給getInstance(context)來解決
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.