简体   繁体   中英

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

I have my MainActivity, ConnectThread and ConnectedThread in separate classes.

I am listening to a lot of data from a Bluetoothmodule in ConnectedThread.

I have the Broadcastreciever in my Main thread like this:

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. The other is just the Bluetooth part which is not relevant here.

I have the Intent in the ConnectedThread like this:

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.

I was trying to use this example: 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)来解决

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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