Android将Thread中的数据从单独的java类发送到UI线程

时间:2016-06-10 08:04:41

标签: java android multithreading bluetooth

我将MainActivity,ConnectThread和ConnectedThread放在不同的类中。

我正在收听ConnectedThread中蓝牙模块的大量数据。

我的主线程中有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中有这样的Intent:

public void sendData(){
    Intent sendDataIntent = new Intent("SendData_EVENT");
    sendDataIntent.putExtra("data",passData);
    LocalBroadcastManager.getInstance().sendBroadcast(sendDataIntent);

}

但由于该线程没有连接到Activity,因此Broadcastmanagers getInstance不起作用。

我试图使用这个例子:LINK

我看了很多例子,我认为处理程序对我来说不是最好的方法。

如何从后台线程成功发送数据?

通过向ConnectedThread构造函数发送getApplicationContext()并将其传递给getInstance(context)来解决此问题

1 个答案:

答案 0 :(得分:0)

通过向ConnectedThread构造函数发送getApplicationContext()并将其传递给getInstance(context)来解决此问题