lwc:programming:mobile:android:runnable

There's nothing special about a Runnable. It's doesn't have anything to do with threads. All it is is an interface, that's it:

  public class MyRunnable implements Runnable {
 
    public void run(){
       Log.v("MyRunnable running");
    }
  }

The interface takes no parameters and returns no parameters. When started it will run whatever magical stuff you put in the run method. Besides the run method you can have a constructor if the spirit moves you.

You can create a runnable so you have something to send on a separate thread. You don't need a runnable to do it, it's just standard convention everybody seems to have agreed upon. Here's a nice friendly runnable to play with:

  public class MyRunnable implements Runnable {
 
    public void run(){
       Log.v("test","MyRunnable running");
    }
  }

3 ways to create an instance of this runnable:

  • Define the class as above and create an instance: Runnable myRunnable = new MyRunnable
  • Skip naming the class but still define it:
Runnable myRunnable =
    new Runnable(){
        public void run(){
            Log.v("Runnable running");
        }
    }
  • do “the lambda”: Runnable myRunnable = () -> { Log.v("Lambda Runnable running"); };

Once you have a runnable or really any function wrapped up all pretty like this you can create a new thread to run it:

Thread thread = new Thread(myRunnable);
thread.start();

Borrowed and reworded from this excellent resource.

  • lwc/programming/mobile/android/runnable.txt
  • Last modified: 2022/02/23 15:31
  • by John Harrison