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

Tags:

Luke Alderton

Comments

Share with
Tags
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
Categories
App Development
Event
Game Development
Mapping
Modelling
Programming
Review
Robotics
Tutorial
Web Development