0

My problem is: I can't figure out a way to restart my activity from itself. For example in a game, if you die, there's a menu with an option to retry, which restart the stage instantly. That's exactly the case.

As i have read from a lot of others answers on this matter, there are 2 main methods for reloading an activity:

1- finish(); startActivity(getIntent());

2- recreate();

The first method doesn't seem to work for me because it restart the activity, but leave the previous created one open on the back of my stack. Looks like the finish() statement is not doing its stuff. I have tried to put it in front, after, and all kind of ways, but it never closes the activity left behind.

On the other hand, the option number 2 cannot be called (as far as i know) from outside the UI thread, and if i do, the app crashes. I tried to call the recreate method using:

    Activity.this.runOnUiThread(new Runnable() {
        public void run() {
            recreate();
        }
    });

But this approach gives me a very awful blinking on my screen. A black screen suddenly appears, and that doesn't seems right.

Gerardpp
  • 45
  • 2
  • 4

2 Answers2

4

Try this:

    Intent intent = getActivity().getIntent();
    getActivity().finish();
    startActivity(intent);
aldakur
  • 419
  • 4
  • 16
  • Thank you for your answer. That is working for me but the activity doesnt close. It keep adding more and more duplicates of the activity onto the stack. – Gerardpp May 02 '15 at 23:28
  • Looks like the answer of aldakur was more acurate to my needs. I just added a little extra line of code on my manifest to make sure the system doesn't accept more instances of that particular activity, using: `android:launchMode="singleInstance"` . – Gerardpp May 03 '15 at 11:23
1

You should add FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK flags to the intent, such as:

Intent intent = getActivity().getIntent();
intent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK);
getActivity().finish();
startActivity(intent);

This will force the system to remove the previous task from the stack.

Kane O'Riley
  • 2,482
  • 2
  • 18
  • 27