0

Options are: using MainActivity.this or passing the context through the Runnable constructor.

1st option:

public class MainActivity extends AppCompatActivity {
    //...
    public void onButtonClick() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SomeMethod(MainActivity.this);
            }
        }).start();
    }
    //...
}

2nd option:

public class MainActivity extends AppCompatActivity {
    //...
    public void onButtonClick() {
        new Thread(new SomeRunnable(this)).start();
    }
    //...
    private class SomeRunnable implements Runnable {
        private final Context context;

        public SomeRunnable(Context context) {
            this.context = context;
        }

        @Override
        public void run() {
            SomeMethod(context);
        }
    }
}

The first option seems a bit more convenient (as it's simply shorter), but could there be any behaviour problems with such code?

2 Answers2

0

The better way is:

public class MainActivity extends AppCompatActivity {
    //...
    public void onButtonClick() {
        new Thread(() -> SomeMethod(this)).start();
    }
    //...
}

Explanation: lambda expression belongs to scope of current method, so it has direct access to this

Daniel Zin
  • 479
  • 2
  • 7
  • Does that mean that in lambda expression we can use "this" as a pointer to the MainActivity context both as argument to an existing method and in anonymous method body? – Andrey Ryzhak May 20 '21 at 12:06
  • In Java "this" is reference, not pointer. Yes, all data members of MainActivity current object and also all local variables are visible in the body of lambda expression in the same way as in the containing method onButtonClick(). The only restriction is: lambda could use only final or effectively final local variables. For more information I propose you to learn the tutorial: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html – Daniel Zin May 24 '21 at 10:03
0

It's good to keep your context in own scope. So if you need context outside of Activity you can use getApplicationContext().

More complex definition was here: What's the difference between the various methods to get a Context?

Sn1cKa
  • 601
  • 6
  • 11