The question that I want to answer with this post is the following: How bundle Android works for exchanging data from a running thread and the main UI.
This is a fairly common situation and very simple to figure it out.
The situation might be the following:
- An Android activity that creates a thread that run do some work
- The created thread has to exchange some data with the main IU thread
This situation can be handled by using a combination of Android bundles and messages. The code of the two Java classes involved in the project might be the following:
[sourcecode language=”java”]
public class MainActivity extends Activity {
private Thread workingthread = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
workingthread=new JobThread();
workingthread.start();
}
}
[/sourcecode]
in which a Thread named workingthread is created and started on the onCreate event. The JobThread might be declared as the following:
[sourcecode language=”cpp”]
public class JobThread extends Thread{
public JobThread(){
//constructor
}
public void run() {
//do some work here
}
}
The key part of every Java threads is the run method. It is invoked once the start method on the workingthread variable is called.
Suppose that the MainActivity needs the results of the computation that is done in the thread. Suppose that the result is a triple of integers.
To figure out this issue Android lets you use the data bundle (to create a rich object that contains structured data) and messages to send the data bundle back to the main UI thread.
To add (integer in my example) values to the bundle, you should use the putInt method together with a key to "name" the data just created (so to retrieve them back). Once the bundle is created and the values added, you can use the sendMessage method to send it back to the UI thread.
The resulting MainActivity and JobThread should look as:
[sourcecode language="java"]
[/sourcecode]
This approach is interesting because it can be used both to send data back to the parent thread but also to update the main UI according to the values received. This is very useful because Android does not allow you to update graphical elements directly from background threads.
Additional references
Async Task