0

In the AppCompatActivity just wanted to get some feedback on this. When does this Runnable run?

Is the super.onBackPressed(); posted on Main ui thread and then my Runnable is also posted to Main ui thread? which I know is a queue right. is this correct?

@Override
public void onBackPressed() {
    super.onBackPressed();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
             // some work
            }
        });
}
Tord Larsen
  • 2,670
  • 8
  • 33
  • 76
  • 1
    code in onBackPressed always will run on UI thread.. – ak sacha Feb 21 '17 at 11:47
  • It's a thread, not a que perse. If you want to access anything in the UI it's required to run things on UI like that. However as you said before it's already on the UI thread because onBackPressed is called from the UI thread – Mathijs Segers Feb 21 '17 at 11:47

1 Answers1

0

onBackPressed() will always be called on UI thread. so runOnUiThread() method is unnecessary here.

What your code does is post the Runnable on the UI thread from UI thread itself

Internally runOnUiThread() does the below action

public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}
arjun
  • 3,514
  • 4
  • 27
  • 48
  • My Q is not so clear but I experience that if I press back button on a Fragment and in the `public void onBackPressed() ` I want to get the current Fragment that now is in `R.id.frame` after `super.onBackPressed();` I have to run this: `FragManager.findFragmentById(R.id.frame);` inside the` runOnUiThread` – Tord Larsen Feb 21 '17 at 12:03
  • `onBackPressed()` will be called only on `Activity` on the `UI thread` so you can run you code without `runOnUiThread()` – arjun Feb 21 '17 at 12:12