简体   繁体   English

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

[英]Android send data from Thread in separate java class to UI thread

I have my MainActivity, ConnectThread and ConnectedThread in separate classes. 我的MainActivity,ConnectThread和ConnectedThread位于单独的类中。

I am listening to a lot of data from a Bluetoothmodule in ConnectedThread. 我正在从ConnectedThread中的Bluetoothmodule监听许多数据。

I have the Broadcastreciever in my Main thread like this: 我的主线程中有如下的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);


    }
};

I would listen to the message and pass it to a textview. 我会听消息并将其传递给textview。 The other is just the Bluetooth part which is not relevant here. 另一个只是蓝牙部分,此处不相关。

I have the Intent in the ConnectedThread like this: 我在ConnectedThread中有这样的意图:

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

}

But as that thread has no connection to an Activity the Broadcastmanagers getInstance doesn't work. 但是由于该线程与Activity没有连接,所以Broadcastmanagers getInstance不起作用。

I was trying to use this example: LINK 我正在尝试使用以下示例: LINK

I had a look on a lot of examples and i don't think handlers are the best method for me. 我看了很多示例,但我认为处理程序不是我的最佳方法。

How can i succesfully send the data from my background Thread? 如何成功从后台线程发送数据?

SOLVED by sending sending getApplicationContext() to ConnectedThread constructor and passing that to getInstance(context) 通过将发送getApplicationContext()发送给ConnectedThread构造函数并将其传递给getInstance(context)来解决

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM