Multiple background threads in Android app
So I ran into an ussie with creating background threads in an android application and found that it's not actualy as difficult to fix as I thought it was, take a look at the code below to see how to do it yourself.
package lukealderton.threadexample;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity
{
// The threads we're going to use
private Thread backgroundProcess1;
private Thread backgroundProcess2;
// Set up vars here that are going to be used within the threads because it
// Will cause an inner class exception
private String myString = "";
// The onCreate method is called when the app starts
@Override
public void onCreate(Bundle savedInstanceState)
{
// Set up the app
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Set up backgroundProcess1 and put the code we need inside it
backgroundProcess1 = new Thread(new Runnable()
{
public void run()
{
// Put code you want here
// set a value of myString
myString = "value";
}
});
// Set up backgroundProcess2 and put the code we need inside it
backgroundProcess2 = new Thread(new Runnable()
{
public void run()
{
// put code you want here
// myString can also be called from here
myString += " with added new value";
}
});
myMethod();
}
public void myMethod()
{
// Put your main code in any function you like but you can now start your
// thread by using the below line of code
backgroundProcess1.start();
// Or this to start the other thread
backgroundProcess2.start();
}
}
Check here to seeĀ how to update the UI from another thread.
Published at 4 Nov 2012, 22:54 PM
Tags: