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.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
    public void onCreate(Bundle savedInstanceState)
        // Set up the app

        // 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";
    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
        // Or this to start the other thread

Check here to seeĀ how to update the UI from another thread.

Published at


Luke Alderton


Share with
Latest Comments
By Mark Gentry on Windows Server 2019 - Change product key does nothing
20 Aug 2021, 03:30 AM
By Cathy on In-Place Upgrade for a Windows Server domain controller
31 Jul 2021, 18:28 PM
By Mr. Greymatter on Raspberry Pi - Running Java app on Raspbian
16 Feb 2021, 07:35 AM
By Mikko Seittenranta on Xamarin Forms multiple instances of same app open
16 Feb 2021, 04:34 AM
By Andrew on Auto/Custom height on Xamarin Forms WebView for Android and iOS
22 Jan 2021, 22:15 PM
By Nick on Raspberry Pi - Running Java app on Raspbian
14 Oct 2020, 19:37 PM
By Ivan on Fixed: Value cannot be null Parameter Name: source
15 Sep 2020, 19:47 PM
By Anand on Raspberry Pi - Bluetooth using Bluecove on Raspbian
7 Sep 2020, 16:53 PM
App Development
Game Development
Web Development