Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - passing data between threads

I need to pass a huge amount of data (raw bytes) between threads - listener thread and another thread that deals with the data manipulation. Whats the best and fastest way to do that?

like image 307
Maayan Castel Avatar asked Jul 17 '26 19:07

Maayan Castel


1 Answers

As others have pointed out it really depends on the task you have. I would suggest using a Message. For example if one of your threads is a producer of said byte[] data and the other is the consumer you may have something of the sorts:

public class ProducerThread extends Thread{
    byte[] data;

    public void run(){
        while (isRunning){
            Looper.prepare(); 
            data = someMethodToGetYourByteData(); 
            Message dataToSend = Message.obtain();
            Bundle bundle = new Bundle();
            bundle.putByteArray("data", data);
            dataToSend.setData(bundle);
            if (ConsumerThread.mHandler!=null){  
               ConsumerThread.mHandler.sendMessage(dataToSend);
            }
            Looper.loop();  
         }
     }

and your consumer thread:

public class ConsumerThread extends Thread{
    public static Handler mHandler;  
    byte[] data;

    public void run(){
       while (running){
          Looper.prepare();
          mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                mHandler.obtainMessage();
                data = msg.getData().getFloatArray("data");
                doSomethingWithData(data);
           };
         }
         Looper.loop();
      }

Keep in mind though that this may not be the best pattern to use, as many elsewhere on SO point out that it is not the best idea to extend a Thread, but it generally depends on the use case.

like image 56
Valkova.V Avatar answered Jul 20 '26 09:07

Valkova.V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!